11 Answers
New AnswerIt will work as you expect, if you cleared the underlying string buffer of <ss2> at line 12 ss2.str( string {} ); clear() method apparently was meant to clear the state flags e.g. error flags etc. It wasn't meant to clear the underlying string buffer. Lisa's way is simpler I think ... https://en.cppreference.com/w/cpp/io/basic_ios/clear
Manav Roy clear your ss2 and ss ss2.clear(); ss2.str(string{}); see my comment on your Hello Bro example.
// I think ss2 needs to be a string and go into the head of the while-loop #include <iostream> #include <sstream> using namespace std; int main() { string s="hello how are you"; stringstream ss(s); string ss2; while(ss>>ss2) { cout << ss2 << endl; } return 0; } // https://www.tutorialspoint.com/stringstream-in-cplusplus
Ipang Hi, https://code.sololearn.com/cc7e9R3dig76/?ref=app I've tried your way to clear the stuffs from string stream, This code should print- 1|1|1, 1|1|1 But why it's only printing- 1|1|1, ??
I couldn't figure out what was wrong with your code, it goes crashing with a message I couldn't understand. https://code.sololearn.com/c51M6TgksDru/?ref=app
Ipang Lisa Let me ask my question in more easy way, https://code.sololearn.com/cY2UK9SRLqQE/?ref=app This code should print Hello Bro But it's only printing Hello I got the reason, It's because of the line "while(getline(ss2,s)) But why??
Sololearn Inc.
535 Mission Street, Suite 1591Send us a message