Why do I need to clear std :: stringstream?

I wrote a short test program to see if I can add to a string using a string stream several times.

In the first version, I got Output1, and I really don't understand why s1 remains empty. I found out that I need to do ss.clear () and then get the expected result in Output2. Can anyone explain why this does not work without the clear? I would expect that if I re-enter numbers and return them back to the string, I should always get the number. I was not sure if the number is being added, but this does not apply to this example.

Here: http://www.cplusplus.com/reference/sstream/stringstream/ it says that I can use any operation and there are no restrictions or requirements for resetting the line I could see. I also don't understand why after that I get output without ss.clear () between them.

I am also a little surprised that s0 remains unchanged. So the thread does not overwrite or reset the line if it already has content?

I am 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 
+7
source share
1 answer

After reading in s0 stream is in the EOF state. Therefore, the next read is not performed if the EOF state is not cleared. Writing to a stream does not clear the read state for you.


Edit only to complete the answer. The behavior comes from the definition of eofbit of ios_base::iostate , which states that the state of the stream will have this bit if the stream is at the end of the input sequence.

In the first version of your program, since the EOF state is not cleared after the first read in s0 , neither the second read nor the third read will be executed. So, the failure of the first read leaves s1 empty, and the failed second read leaves s0 unchahnged.

In the second version of your program, you clear ss after the first read in s0 , which allows you to perform a second read in s1 . However, after the second read, the thread is again in the EOF state, so the third read is not performed. This leaves s0 unchanged.

+5
source

All Articles