< previous page page_213 next page >

Page 213
Testing the State of an I/O Stream
In Chapter 4, we talked about the concept of input and output streams in C++. We introduced the data types istream, ostream, ifstream, and ofstream. We said that any of the following can cause an input stream to enter the fail state:
Invalid input data
An attempt to read beyond the end of a file
An attempt to open a nonexistent file for input
C++ provides a way in which to determine if a stream is in the fail state. In a logical expression, you simply use the name of the stream variable as if it were a Boolean variable:
if (cin)
  .
  .
  .
if ( !inFile )
  .
  .
  .
When you do this, you are said to be testing the state of the stream. The result of the test is either a nonzero value (meaning the last I/O operation on that stream succeeded) or zero (meaning the last I/O operation failed).
Conceptually, you want to think of a stream variable in a logical expression as being a Boolean variable with a value TRUE (the stream state is okay) or FALSE (the state isn't okay).
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif 3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
Testing the State of a Stream The act of using a C++ stream variable in a logical expression as if it were a Boolean variable; the result is nonzero (TRUE) if the last I/O operation on that stream succeeded, and zero (FALSE) otherwise.
In an If statement, the way you phrase the logical expression depends on what you want the then-clause to do. The statement

 
< previous page page_213 next page >