Why do I have to clear std::stringstream here?

孤街浪徒 提交于 2020-01-03 10:04:34

问题


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

回答1:


After the read into s0, the stream is in the EOF state. So the next read fails unless the EOF state is cleared. Writing to the stream does not clear the read state for you.


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

In the first version of your program, since the EOF state is not cleared after the first read into s0, neither the second read nor the third read will succeed. So, the failed 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 into s0, which allows the second read into s1 to succeed. However, after the second read, the stream is in the EOF state again, so the third read fails. This leaves s0 unchanged.



来源:https://stackoverflow.com/questions/16443153/why-do-i-have-to-clear-stdstringstream-here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!