Stream State or I/O state

There are 4 states available in the stream states. 

  • End of file (eof)
  • No errors (good)
  • Logical error (fail)
  • Read/writing error (bad)


Here, good is not the opposite of bad because bad checks whether a badbit is set or not.

When eof, fail and bad are not true, it means true. 

For debugging the below program click here

#include <iostream>
#include <sstream>

using namespace std;

int main(int argc, char** argv)
{
    stringstream ifs{"hello"};
    
    if (ifs.bad() == true || ifs.eof() == true || ifs.fail() == true) {
        cout << "ifs state is bad" << endl;
    } else {
        cout << "ifs state is good" << endl;  
    }
    
    ifs << "shirley";
    ifs.clear(ifs.eofbit); // Set the eofbit
    if (ifs.bad() == true || ifs.eof() == true || ifs.fail() == true) {
        cout << "Shirley: ifs state is bad" << endl;
    } else {
        cout << "Shirley: ifs state is good" << endl;  
    }
    
    return 0;
}

Output

ifs state is good
Shirley: ifs state is bad


Click here for other examples in stringstream

Note: The above program is not an optimised code. In the real environment, we can just check if it is not good, return error/nullptr instead of checking all three bits. 



Comments