|
|
|
|
|
|
|
value, is used to signal the program that there is no more data to be processed. Looping continues as long as the data value read is not the sentinel; the loop stops when the program recognizes the sentinel. In other words, reading the sentinel value is the event that controls the looping process. |
|
|
|
|
|
|
|
|
A sentinel value must be something that never shows up in the normal input to a program. For example, if a program reads calendar dates, we could use February 31 as a sentinel value: |
|
|
|
|
|
|
|
|
// This code is incorrect:
while ( !(month == 2 && day == 31) )
{
cin >> month >> day; // Get a date
.
. // Process it
.
} |
|
|
|
|
|
|
|
|
There is a problem in the loop in the example above. The values of month and day are not defined before the first pass through the loop. Somehow we have to initialize these variables. We could assign them arbitrary values, but then we would run the risk of those values being processed as data. Also, it's inefficient to initialize variables with values that are never used. |
|
|
|
|
|
|
|
|
We can solve the problem by reading the first set of data values before entering the loop. This is called a priming read. (The idea is similar to priming a pump by pouring a bucket of water into the mechanism before starting it.) Let's add the priming read to the loop: |
|
|
|
|
|
|
|
|
// This is still incorrect:
cin >> month >> day; // Get a date--priming read
while ( !(month == 2 && day == 31) )
{
cin >> month >> day; // Get a date
.
.
. // Process it
} |
|
|
|
|
|
|
|
|
There is still a problem here. Notice that the first thing the program does inside the loop is to get a date, destroying the values obtained by the priming read. Thus, the first date in the data list is never processed. Given the priming read, the first thing that the loop body should do is process the data that have already been read. But then at what point do we read the next data set? We do this last. In this way, the While condition is applied to the next data set before it gets processed. Here's how it looks: |
|
|
|
|
|