获取stringstream c ++的剩余部分

时间:2013-04-18 03:04:46

标签: c++ string stringstream

我有一个字符串流,我需要将第一部分输出,然后将剩余部分放入一个单独的字符串中。例如,我有字符串"This is a car",我需要最终得到2个字符串:a = "This"b = "is a car"

当我使用stringstream使用<<获取第一部分时,我使用.str()转换为字符串,这当然给了我整个事情“This is a car"。怎么能我按照我想要的方式来玩它?

4 个答案:

答案 0 :(得分:4)

string str = "this is a car";

std::stringstream ss;
ss << str;

string a,b;
ss >> a;
getline(ss, b);

编辑:感谢@Cubbi:

ss >> a >> ws;

修改

此解决方案可以在某些情况下处理换行符(例如我的测试用例)但在其他情况下失败(例如@ rubenvb的示例),我还没有找到一种干净的方法来解决它。 我认为@ tacp的解决方案更好,更强大,应该被接受。

答案 1 :(得分:2)

你可以这样做:首先获取整个字符串,然后获取第一个单词,使用substr来完成剩下的工作。

 stringstream s("This is a car");
 string s1 = s.str();
 string first;
 string second;

 s >> first;
 second = s1.substr(first.length());
 cout << "first part: " << first <<"\ second part: " << second <<endl;

在gcc 4.5.3输出中测试:

first part: This 
second part: is a car

答案 2 :(得分:1)

在读完第一位后,你可以在流上做getline ....

答案 3 :(得分:0)

另一种方法是使用rdbuf:

stringstream s("This is a car");
string first;
stringstream second;

s >> first;
second << s.rdbuf();
cout << "first part: " << first << " second part: " << second.str() << endl;

如果您最终要将结果输出到流而不是字符串,这可能是一个不错的选择。

相关问题