I wrote a short testprogram to see if I can append to a string using stringstream repeatedly.
In the first version I got Output1 and I don't really understand why s1 stays empty. I found out that I have to do ss.clear() and then get the expected result in Output2. Can anybody explain why it doesn't work without the clear? I would have expected that, If I repeatedly enter numbers and fetch them back into a string, I should get always the number. I was unsure if the number gets appended, but that is beside the point for this example.
Here: http://www.cplusplus.com/reference/sstream/stringstream/ it says I can use any operation, and there is no limitation or requirement to reset the string, I could see. I also don't understand why afterwards I get the output without the ss.clear() in between.
Also I'm a bit surprised that s0 stays the same afterwards. So a stream doesn't overwrite or reset the string if it already has content?
I'm using gcc 3.4.4 with cygwin.
int main()
{
std::string s0;
std::string s1;
int n = 1;
std::stringstream ss;
ss << n;
ss >> s0;
cout << "S0:" << s0 << endl;
ss.clear(); <-- If I remove this, then s1 stays empty.
n = 2;
ss << n;
ss >> s1;
cout << "S1:" << s1 << endl;
ss << n;
ss >> s0;
cout << "S0_2:" << s0 << endl; <-- Why is s0 still 1?
}
Output1:
S0:1
S1:
S0_2:1
Output2:
S0:1
S1:2
S0_2:1