Does stringstream.read() consume the stream?

泄露秘密 提交于 2020-05-15 02:05:53

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!