Why does string extraction from a stream set the eof bit?

前端 未结 2 1322
梦如初夏
梦如初夏 2020-12-31 13:29

Let\'s say we have a stream containing simply:

hello

Note that there\'s no extra \\n at the end like there often is in a text

相关标签:
2条回答
  • 2020-12-31 14:05

    Intuitively speaking, the EOF bit is set because during the read operation to extract the string, the stream did indeed hit the end of the file. Specifically, it continuously read characters out of the input stream, stopping because it hit the end of the stream before encountering a whitespace character. Accordingly, the stream set the EOF bit to mark that the end of stream was reached. Note that this is not the same as reporting failure - the operation was completed successfully - but the point of the EOF bit is not to report failure. It's to mark that the end of the stream was encountered.

    I don't have a specific part of the spec to back this up, though I'll try to look for one when I get the chance.

    0 讨论(0)
  • 2020-12-31 14:25

    std::stringstream is a basic_istream and the operator>> of std::string "extracts" characters from it (as you found out).

    27.7.2.1 Class template basic_istream

    2 If rdbuf()->sbumpc() or rdbuf()->sgetc() returns traits::eof(), then the input function, except as explicitly noted otherwise, completes its actions and does setstate(eofbit), which may throw ios_- base::failure (27.5.5.4), before returning.

    Also, "extracting" means calling these two functions.

    3 Two groups of member function signatures share common properties: the formatted input functions (or extractors) and the unformatted input functions. Both groups of input functions are described as if they obtain (or extract) input characters by calling rdbuf()->sbumpc() or rdbuf()->sgetc(). They may use other public members of istream.

    So eof must be set.

    0 讨论(0)
提交回复
热议问题