Program Notes

The heart of the error-handling code in Listing 6.14 is the following:

while (!(cin >> golf[i])) {
    cin.clear();     // reset input
    while (cin.get() != ' ')
        continue; // get rid of bad input
    cout << "Please enter a number: ";
}

If the user enters 88, the cin expression is true, and a value is placed in the array. Furthermore, because cin is true, the expression !(cin >> golf[i]) is false, and this inner loop terminates. But if the user enters must i?, the cin expression is false, nothing is placed into the array, the expression !(cin >> golf[i]) is true, and the program enters the inner while loop. The first statement in the loop uses the clear() method to reset input. If you omit this statement, the program refuses to read any more input. Next, the program uses cin.get() in a while loop to read the remaining input through the end of the line. This gets rid of the bad input, along with anything else on the line. Another approach is to read to the next whitespace, which gets rid of bad input one word at a time instead of one line at a time. Finally, the program tells the user to enter a number.

Simple File Input/Output

Sometimes keyboard input is not the best choice. For example, suppose you’ve written a program to analyze stocks, and you’ve downloaded a file of 1,000 stock prices. It would be far more convenient to have the program read the file directly than to hand-enter all the values. Similarly, it can be convenient to have a program write output to a file so that you have a permanent record of the results.

Fortunately, C++ makes it simple to transfer the skills you’ve acquired for keyboard input and display output (collectively termed console I/O) to file input and output (file I/O). Chapter 17 explores these topics more extensively, but we’ll look at simple text file I/O now.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.27.251