< previous page page_264 next page >

Page 264
third time, printing the value 30 and executing the input statement. This time, the input statement fails; we're trying to read beyond the end of the file. The stream inData enters the fail state. Looping back to the loop test, the value of the expression is zero (FALSE) and we exit the loop.
When we write EOF-controlled loops like the one above, we are expecting that end-of-file is the reason for stream failure. But keep in mind that any input error causes stream failure. The above loop terminates, for example, if input fails because of invalid characters in the input data. This fact emphasizes again the importance of echo printing. It helps us verify that all the data were read correctly before EOF was encountered.
EOF-controlled loops are similar to sentinel-controlled loops in that the program doesn't know in advance how many data items are to be input. In the case of sentinel-controlled loops, the program reads until it encounters the sentinel value. With EOF-controlled loops, it reads until it reaches the end of the file.
Is it possible to use an EOF-controlled loop when we read from the standard input device (via the cin stream) instead of a data file? On many systems, yes. With the UNIX operating system, you can type Ctrl/D (that is, you hold down the Ctrl key and tap the D key) to signify end-of-file during interactive input. With the MS-DOS operating system, the end-of-file keystrokes are Ctrl/Z. Other systems use similar keystrokes. Here's a program segment that tests for EOF on the cin stream in UNIX:
cout << Enter an integer (or Ctrl/D to quit): ;
cin >> someInt;
while (cin)
{
    cout << someInt <<  doubled is  << 2 * someInt << endl;
    cout << Next number (or Ctrl/D to quit): ;
    cin >> someInt;
}
Flag-Controlled Loops
A flag is a Boolean variable that is used to control the logical flow of a program. We can set a Boolean variable to TRUE before a While loop; then, when we want to stop executing the loop, we reset it to FALSE. That is, we can use the Boolean variable to record whether or not the event that controls the process has occurred. For example, the following program segment reads and sums values until the input value is negative. (nonNegative is the Boolean flag; all of the other variables are of type int.)
sum = 0;
nonNegative = TRUE;              // Initialize flag
while (nonNegative)
{
    cin >> number;

 
< previous page page_264 next page >