[   ^ to index...   |   <-- previous   |   next -->   ]

Controlling streams

Checking stream status

You can get the status of an input stream in a number of ways. The most straightforward is to test it as a boolean value:

if (cin) // some stuff if (cin >> i) // Recall that >> returns an istream & // some stuff

What's happening here? Well, you should be familiar with automatic type conversions---for example, when you evaluate the expression "2 * 3.0", you know that the 2 will be converted to the equivalent floating-point value 2.0 before the operation.

C++ allows the programmer to define conversions between user-defined types as well. In particular, there is an automatic conversion defined between istream and bool. The resulting boolean value is true if the last operation succeeded, false otherwise.

All I/O streams also define the following status functions:

class basic_ios { // This line is a lie bool good() const; // Next operation might succeed bool eof() const; // End of file encountered bool fail() const; // Next operation will fail bool bad() const; // Stream is corrupted (implies fail()) void clear(); // Clear status flags. (This line is a lie) };
Q: What is the difference between fail() and bad()?
A: fail() implies that no characters have been lost, but the next operation will fail. bad() implies that all bets are off. Your computer is permitted to lose data or even spontaneously explode if you attempt to read from this stream again.


Q: How is evaluating !cin.fail() different from evaluating cin in a boolean context?
A: Actually, they're identical.

Last modified: Wed Jun 28 19:31:54 PDT 2000