I can't tell from the documentation how std::stringstream.read()
works. Does it consume the stream or not?
In other words:
std::stringstream ss;
char buffer[6];
ss << "Hello world!";
ss.read(buffer, 6);
std::cout << ss.str(); // Is this "Hello world!" or just "world!"
The member std::istream::read()
advances the stream position for as many characters it returns. I guess, this is what you mean with "consuming the stream". After reading 6 characters from ss
, the next character read will be the w
.
However, the string stream's internal buffer is still the entire string, i.e., the result of str()
is unaffected by the read position: std::stringstream::str()
returns all characters. In 27.8.2.3 [stringbuf.members] paragraph 1 it says:
basic_string<charT,traits,Allocator> str() const;
Returns: A basic_string object whose content is equal to the basic_stringbuf underlying character sequence. ...
The paragraph goes on describing what the underlying character sequence is but it amounts to: the entire original string in input mode and the original characters plus additional written characters in output mode.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With