Go to the first, previous, next, last section, table of contents.

Checking the state of a stream

Use this collection of methods to test for (or signal) errors and other exceptional conditions of streams:

Method: ios::operator void* () const

You can do a quick check on the state of the most recent operation on a stream by examining a pointer to the stream itself. The pointer is arbitrary except for its truth value; it is true if no failures have occurred (ios::fail is not true). For example, you might ask for input on cin only if all prior output operations succeeded:

if (cout)
{
  // Everything OK so far
  cin >> new_value;
  ...
}

Method: ios::operator ! () const

In case it is more convenient to check whether something has failed, the operator ! returns true if ios::fail is true (an operation has failed). For example, you might issue an error message if input failed:

if (!cin)
{
  // Oops
  cerr << "Eh?\n";
}

Method: iostate ios::rdstate () const

Return the state flags for this stream. The value is from the enumeration iostate. You can test for any combination of

goodbit
There are no indications of exceptional states on this stream.
eofbit
End of file.
failbit
An operation has failed on this stream; this usually indicates bad format of input.
badbit
The stream is unusable.

Method: void ios::setstate (iostate state)

Set the state flag for this stream to state in addition to any state flags already set. Synonym (for upward compatibility): ios::set.

See ios::clear to set the stream state without regard to existing state flags. See ios::good, ios::eof, ios::fail, and ios::bad, to test the state.

Method: int ios::good () const

Test the state flags associated with this stream; true if no error indicators are set.

Method: int ios::bad () const

Test whether a stream is marked as unusable. (Whether ios::badbit is set.)

Method: int ios::eof () const

True if end of file was reached on this stream. (If ios::eofbit is set.)

Method: int ios::fail () const

Test for any kind of failure on this stream: either some operation failed, or the stream is marked as bad. (If either ios::failbit or ios::badbit is set.)

Method: void ios::clear (iostate state)

Set the state indication for this stream to the argument state. You may call ios::clear with no argument, in which case the state is set to good (no errors pending).

See ios::good, ios::eof, ios::fail, and ios::bad, to test the state; see ios::set or ios::setstate for an alternative way of setting the state.


Go to the first, previous, next, last section, table of contents.