Search code examples
c++stringstream

c++: stream output operation successful but state not good


I am trying to learn more about stream states and read here that good() returns true if the the most recent I/O operation on the stream completed successfully. I have tried to following which, if I understand correctly, goes against the above statement

#include <iostream>
#include <sstream>


int main() {

    std::stringstream ss;
    int x;

    ss << "42";
    ss >> x;

    std::cout << x << std::endl; // prints 42 as expected
    std::cout << ss.good() << std::endl; // prints 0, expected 1

    return 0;
}

Could someone clarify why the stream state is not good even though the last (output) operation was successful? Thank you


Solution

  • The reason why EOF is not set until the next extraction for a file stream is not because there is any difference in behavior between file/string streams, but because many text editors secretly insert a newline at the end of a file. Try creating a text file with the contents:

    a
    b
    

    And then inspecting it with something like od -c and you might see:

    0000000   a  \n   b  \n
    0000004
    

    Notice the sneaky newline after b. If you insert a newline at the end of your stringstream, you should observe the same behavior.