Contents|Index|Previous|Next

Checking the state of a stream

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

    ios::operator void* () const
    Method

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 instance, you might ask for input on cin only if all prior output operations succeeded, as in the following example.

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

    ios::operator ! () const
    Method

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, as in the following example.

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

    iostate ios::rdstate ()const
    Method

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

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

    void ios::setstate (iostate state)
    Method

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.

    int ios::good ()const
    Method

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

    int ios::bad ()const
    Method

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

    int ios::eof ()const
    Method

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

    int ios::fail ()const
    Method

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.)

    void ios::clear (iostate state)
    Method

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.