|
|
|
|
|
|
|
(interpreted by the computer as TRUE), and its side effect is to store the value 1 into sentinel, replacing the value that was just input into the variable. Because the While expression is always TRUE, the loop never stops. |
|
|
|
|
|
|
|
|
End-of-File-Controlled Loops |
|
|
|
|
|
|
|
|
You already have learned that an input stream (such as cin or an input file stream) goes into the fail state (a) if it encounters unacceptable input data, (b) if the program tries to open a nonexistent input file, or (c) if the program tries to read past the end of an input file. Let's look at the third of these three possibilities. |
|
|
|
|
|
|
|
|
After a program has read the last piece of data from an input file, the computer is at the end of the file (EOF, for short). At this moment, the stream state is all right. But if we try to input even one more data value, the stream goes into the fail state. We can use this fact to our advantage. To write a loop that inputs an unknown number of data items, we can use the failure of the input stream as a sentinel. |
|
|
|
|
|
|
|
|
In Chapter 5, we described how to test the state of an I/O stream. In a logical expression, we use the name of the stream as though it were a Boolean variable: |
|
|
|
|
|
|
|
|
In a test like this, the result is nonzero (TRUE) if the most recent I/O operation succeeded, or zero (FALSE) if it failed. In a While statement, testing the state of a stream works the same way. Suppose we have a data file containing integer values. If inData is the name of the file stream in our program, here's a loop that reads and echoes all of the data values in the file: |
|
|
|
|
|
|
|
|
inData >> intVal; // Get first value
while (inData) // While the input succeeded
{
cout << intVal << endl; // Echo it
inData >> intVal; // Get next value
} |
|
|
|
|
|
|
|
|
Let's trace this code, assuming there are three values in the file: 10, 20, and 30. The priming read inputs the value 10. The While condition is TRUE because the input succeeded. Therefore, the computer executes the loop body. First the body prints out the value 10, and then it inputs the second data value, 20. Looping back to the loop test, the expression inData is TRUE because the input succeeded. The body executes again, printing the value 20 and reading the value 30 from the file. Looping back to the test, the expression is TRUE. Even though we are at the end of the file, the stream state is still okaythe previous input operation succeeded. The body executes a |
|
|
|
|
|