Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does stringstream.read() consume the stream?

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!"
like image 454
chowey Avatar asked Feb 14 '23 16:02

chowey


1 Answers

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.

like image 187
Dietmar Kühl Avatar answered Feb 24 '23 18:02

Dietmar Kühl