< previous page page_262 next page >

Page 262
{
    .
    .
    .                               // Process it
    cin >> dataValue >> sentinel;   // Get next data value
}
The second value on each line of the following data set is used to indicate whether or not there are more data. In this data set, when the sentinel value is 0, there are no more data; when it is 1, there are more data.
Data values
Sentinel values
0262-01.gif
0262-02.gif
10
1
0
1
-5
1
8
1
-1
1
47
0

What happens if you forget to enter the sentinel value? In an interactive program, the loop executes again, prompting for input. At that point, you can enter the sentinel value, but your program logic may be wrong if you already entered what you thought was the sentinel value. If the input to the program is from a file, once all the data have been read from the file, the loop body is executed again. However, there aren't any data leftbecause the computer has reached the end of the fileso the file stream enters the fail state. In the next section, we describe a way to use the end-of-file situation as an alternative to using a sentinel.
Before we go on, we mention an issue that is related not to the design of loops but to C++ language usage. In Chapter 5, we talked about the common mistake of using the assignment operator (=) instead of the relational operator (==) in an If condition. This same mistake can happen when you write While statements. See what happens when we use the wrong operator in the previous example:
cin >> dataValue >> sentinel;
while (sentinel = 1)               // Whoops
{
    .
    .
    .
    cin >> dataValue >> sentinel;
}
This mistake creates an infinite loop. The While expression is now an assignment expression, not a relational expression. The expression's value is 1

 
< previous page page_262 next page >