Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the remainder of a stringstream c++

I have a stringstream where I need to get the first part out and then get the remainder into a separate string. For example I have the string "This is a car" and I need to end up with 2 strings: a = "This" and b = "is a car".

When I use stringstream to get the first part using <<,then I use the .str() to convert to a string which of course gave me the whole thing "This is a car". How can I get it to play how I want?

like image 989
Linkandzelda Avatar asked Apr 18 '13 03:04

Linkandzelda


2 Answers

string str = "this is a car";

std::stringstream ss;
ss << str;

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

EDIT: correction thanks to @Cubbi:

ss >> a >> ws;

EDIT:

This solution can handle newlines in some cases (such as my test cases) but fails in others (such as @rubenvb's example), and I haven't found a clean way to fix it. I think @tacp's solution is better, more robust, and should be accepted.

like image 72
Beta Avatar answered Sep 21 '22 19:09

Beta


You can do this: first get the whole string, then get the first word, using substr to get the rest.

 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;

Testing this in gcc 4.5.3 outputs:

first part: This 
second part: is a car
like image 25
taocp Avatar answered Sep 21 '22 19:09

taocp