Why this output? | Sololearn: Learn to code for FREE!

+3

Why this output?

I want my code to print - Hello How Are You But why I'm not getting desired output? https://code.sololearn.com/cc2NRrb1NRcR/?ref=app

c++

7/2/2022 8:40:15 AM

Manav Roy

11 Answers

New Answer

+4

It 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

+3

Manav Roy clear your ss2 and ss ss2.clear(); ss2.str(string{}); see my comment on your Hello Bro example.

+2

// 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

+2

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, ??

+2

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

+1

ss is the stringstream

+1

Ipang Thank you very much :)

+1

No problem : )

+1

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??

+1

Bob_Li Thanks a ton Bob li 🙏🙏

0

Lisa Actually,I want to achieve this task with string stream object.