用stringstream更容易:
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
using namespace std;
vector<string> svec;
void reverse(string s)
{
istringstream istream(s);
string word;
while(istream>>word)
svec.push_back(word);
vector<string>::const_reverse_iterator iter =svec.rbegin();
while(iter!=svec.rend())
{cout<<*iter<<ends;
++iter;
}
cout<<endl;
}
int main()
{
string student("I am a student.");
reverse(student);
return 0;
}
istringstream对象可以绑定一行字符串,然后以空格为分隔符把该行分隔开来。
#include<iostream> #include<sstream> using namespace std; int main() { string str, line; while(getline(cin, line)) { istringstream stream(line); while(stream>>str) cout<<str.c_str()<<endl; } return 0; }
测试:
input:
abc df e efgeg ffg
ouput:
abc
df
e
efgeg
ffg