直接读,一般读取都是自动以空格、tab、换行为分隔读取的,然后只需要输出的时候只输出空格即可:
string str;
while(cin>>str) { //这里自动会按照空格、tab、换行为分隔读取字符串
cout<<str<<" "; //输出的时候输出成一行就行了
}
cout<<endl;
如果是从文件读,就把cin换成一个ifstream的对象就行:
#include <fstream>
...
ifstream infile("test.txt");
string str;
while(infile>>str) { //这里自动会按照空格、tab、换行为分隔读取字符串
cout<<str<<" "; //输出的时候输出成一行就行了
}
cout<<endl;
如果是从字符串里读,用stringstream就可以:
#include <sstream>
...
stringstream ss("This is text for test\nA new line here\nAnother new line here");
string str;
while(ss>>str) { //这里自动会按照空格、tab、换行为分隔读取字符串
cout<<str<<" "; //输出的时候输出成一行就行了
}
cout<<endl;