c++ - Why do I have to clear std::stringstream here? -
i wrote short testprogram see if can append string using stringstream repeatedly.
in first version got output1 , don't understand why s1 stays empty. found out have ss.clear() , expected result in output2. can explain why doesn't work without clear? have expected that, if repeatedly enter numbers , fetch them string, should number. unsure if number gets appended, beside point example.
here: http://www.cplusplus.com/reference/sstream/stringstream/ says can use operation, , there no limitation or requirement reset string, see. don't understand why afterwards output without ss.clear() in between.
also i'm bit surprised s0 stays same afterwards. stream doesn't overwrite or reset string if has content?
i'm using gcc 3.4.4 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 remove this, s1 stays empty. n = 2; ss << n; ss >> s1; cout << "s1:" << s1 << endl; ss << n; ss >> s0; cout << "s0_2:" << s0 << endl; <-- why s0 still 1? }
output1:
s0:1 s1: s0_2:1
output2:
s0:1 s1:2 s0_2:1
after read s0
, stream in eof state. next read fails unless eof state cleared. writing stream not clear read state you.
edit complete answer. behavior comes definition of eofbit
of ios_base::iostate
says state of stream have bit set if stream @ end of input sequence.
in first version of program, since eof state not cleared after first read s0
, neither second read nor third read succeed. so, failed first read leaves s1
empty, , failed second read leaves s0
unchahnged.
in second version of program, clear ss
after first read s0
, allows second read s1
succeed. however, after second read, stream in eof state again, third read fails. leaves s0
unchanged.
Comments
Post a Comment