< previous page page_261 next page >

Page 261
// This version is correct:

cin >> month >> day;                    // Get a date--priming read
while ( !(month == 2 && day == 31) )
{
    .
    .
    .                                   // Process it
    cin >> month >> day;                // Get the next date
}
This segment works fine. The first data set is read in; if it is not the sentinel, it gets processed. At the end of the loop, the next data set is read in, and we go back to the beginning of the loop. If the new data set is not the sentinel, it gets processed just like the first. When the sentinel value is read, the While expression becomes FALSE, and the loop exits (without processing the sentinel).
Many times the problem dictates the value of the sentinel. For example, if the problem does not allow data values of 0, then the sentinel value should be 0. Sometimes a combination of values is invalid. The combination of February and 31 as a date is such a case. Sometimes a range of values (negative numbers, for example) is the sentinel. And when you process char data, one line of input at a time, the newline character (\n] often serves as the sentinel. Here's a code segment that reads and prints all of the characters on an input line (inChar is of type char):
cin.get(inChar);                 // Get first character
while (inChar != \n)
{
     cout << inChar;             // Echo it
     cin.get(inChar);            // Get next character
}
(Notice that for this particular task we use the get function, not the >> operator, to input a character. Remember that the >> operator skips whitespace charactersincluding blanks and newlinesto find the next data value in the input stream. In this example, we want to input every character, even a blank and especially the newline character.)
When you are choosing a value to use as a sentinel, what happens if there aren't any invalid data values? Then you may have to input an extra value in each iteration, a value whose only purpose is to signal the end of the data. For example, look at this code segment:
cin >> dataValue >> sentinel;       // Get first data value
while (sentinel == 1)

 
< previous page page_261 next page >