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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With