问题
I am trying to understand the details of the stringstream in C++. But I find a trouble when I tried to re-input ("<<") the stringstream object. (i.e. the content of the obj still remains the same.) My code is as follows. Outputs are shown in comments.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
stringstream sso;
cout <<"orginal: " << sso.str() <<endl; //orginal:"empty"
sso << "A" << " " << "B" << " " << "C";
cout <<"flowin:" << sso.str() <<endl; //flowin:A B C
string r1, r2, r3;
sso >> r1 >> r2 >> r3;
cout << "flowout:" << r1 << r2 << r3 << endl;//flowout:ABC
cout << "base: " << sso.str() << endl; //base: A B C
cout << "----problem here-----" << endl;
sso << "D" << " " << "E" << " " << "F";
cout <<"flowin:" << sso.str() <<endl; //flowin:A B C
cout << "----this works-----" << endl;
sso.clear(); //clear flag
sso.str(""); //clear content
sso << "D" << " " << "E" << " " << "F";
cout <<"flowin:" << sso.str() <<endl; //flowin:D E F
return 0;
}
Why? I don't understand the result in "---problem here---". Why doesn't the sso accept new inputs?
Apprecited,
回答1:
The last read of sso >> r1 >> r2 >> r3; puts the stream into fail state because no more characters were available while it was still trying to read more characters for r3.
In fail state the stream cannot be written to or read from. To fix your problem move sso.clear(); up to before sso << "D".
You can see different behaviour if you output an extra space after C because then the stream does not enter fail state (it successfully reads r3 while there is still the space in the stream).
来源:https://stackoverflow.com/questions/41627448/c-why-re-input-stringstream-doesnt-work-the-content-remains-the-same