Let's first examine how you can check for errors using the stream state. A stream has several member functions for this purpose, which are summarized with their effects in Table 10:
ios_base member function | Effect |
bool good() |
TRUE if no error flag is set |
bool eof() |
TRUE if eofbit is set |
bool fail() |
TRUE if failbit or badbit is set |
bool bad() |
TRUE if badbit is set |
bool operator!() |
As fail() |
operator void*() |
Null pointer if fail() and non-null value otherwise |
iostate rdstate() |
Value of stream state |
It is a good idea to check the stream state in some central place, for example:
if (!cout) error();
The state of cout is examined with operator!(), which returns TRUE if the stream state indicates that an error occurred.
An ostream can also appear in a boolean position to be tested as follows:
if (cout << x) // okay!
The magic here is the operator void*() that returns a nonzero value when the stream state is nonzero.
Finally, the explicit member functions can also be used:
if (cout << x, cout.good()) // okay!;
Note that there is a difference between good() and operator!(). The function good() takes all flags into account; operator!() and fail() ignore eofbit.
OEM Edition, ©Copyright 1999, Rogue Wave Software, Inc.
Contact Rogue Wave about documentation or support issues.