Let's first examine how you can check for errors using the stream state. Each steram class template inherits several member functions from the basic_ios template for this purpose, which are summarized with their effects in Table 31:
|ios_base member function||Effect|
true if no error flag is set, false otherwise
true if eofbit is set, false otherwise
true if failbit or badbit is set, false otherwise
true if badbit is set, false otherwise
Null pointer if fail() and non-null value otherwise
Value of stream state
It is a good idea to check the stream state in some central place, for example:
if (!std::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 (std::cout << x) // okay!
The magic here is the operator void*(), which returns a nonzero value when the stream state is nonzero.
Finally, the explicit member functions can also be used:
if ((std::cout << x).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.