stringstream reuse
-
Hello! Why doesn't this work? First time it works, second time it returns blanks. std::stringstream s1(std::stringstream::in | std::stringstream::out); s1<<"hello"; string x1; s1>>x1; //x1 contains hello. good s1<<"more"; string x2; s1>>x2; //nope. x2 contains blank Thanks -Rob
-
Hello! Why doesn't this work? First time it works, second time it returns blanks. std::stringstream s1(std::stringstream::in | std::stringstream::out); s1<<"hello"; string x1; s1>>x1; //x1 contains hello. good s1<<"more"; string x2; s1>>x2; //nope. x2 contains blank Thanks -Rob
The code fails because the first 'read' operation on the stringstream results in 'eof'. The following line :
string x1;
s1>>x1; //x1 contains hello. goodcauses the stream to the 'drained', so 'eof' is set. The next 'write' to the stream does not reset the 'eof' bit, so when you try the next 'read' :
string x2;
s1>>x2;It fails because the inputbuffer of the stream has it's 'eof' bit set. I am not sure it is possible to work around this - as far as I know, it is not the intention of 'stringstream' to allow constant intermingling of 'reads' and 'writes' to the underlying string. I would think that once the stream has been 'drained', you need to either recreate or reinitialise the stream. ----------------------- The sermon on the mount... Man 1 : Hear that? Blessed are the greek. Man 2 : The greek? Man 1 : Well apparently, he's going to inherit the earth. Man 2 : Did anyone catch his name?
-
The code fails because the first 'read' operation on the stringstream results in 'eof'. The following line :
string x1;
s1>>x1; //x1 contains hello. goodcauses the stream to the 'drained', so 'eof' is set. The next 'write' to the stream does not reset the 'eof' bit, so when you try the next 'read' :
string x2;
s1>>x2;It fails because the inputbuffer of the stream has it's 'eof' bit set. I am not sure it is possible to work around this - as far as I know, it is not the intention of 'stringstream' to allow constant intermingling of 'reads' and 'writes' to the underlying string. I would think that once the stream has been 'drained', you need to either recreate or reinitialise the stream. ----------------------- The sermon on the mount... Man 1 : Hear that? Blessed are the greek. Man 2 : The greek? Man 1 : Well apparently, he's going to inherit the earth. Man 2 : Did anyone catch his name?
-
Must be getting sleepy - should have thought of 'clear()'!!! ----------------------- The sermon on the mount... Man 1 : Hear that? Blessed are the greek. Man 2 : The greek? Man 1 : Well apparently, he's going to inherit the earth. Man 2 : Did anyone catch his name?