问题
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!"
回答1:
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.
回答2:
Yes it consumes the stream.
However str() function returns complete string in buffer.
You can use ss.rdbuf()->in_avail() to get size of data available after read/>> operations:
ss << "Hello world!";
ss.read(buffer, 6);
std::cout << ss.rdbuf()->in_avail(); // 6 characters available ("world!").
回答3:
read
is an unformmatted input function; it extracts a specified amount of characters from the internal buffer into the byte array that you supply. In this case, it extracts 6 characters from the buffer into buffer
. So the content of buffer
will be "Hello "
.
The opposite goes for write
. write
will insert a specified amount of characters from the supplied byte array into the internal buffer of the output stream.
来源:https://stackoverflow.com/questions/20011851/does-stringstream-read-consume-the-stream