|
|
|
|
|
|
|
the computer has hung, when, in fact, it is working just fine, silently waiting for keyboard input. |
|
|
|
|
|
|
|
|
When a program inputs data from the keyboard or an input file, things can go wrong. Let's suppose that we're executing a program. It prompts us to enter an integer value, but we absentmindedly type some letters of the alphabet. The input operation fails because of the invalid data. In C++ terminology, the cin stream has entered the fail state. Once a stream has entered the fail state, any further I/O operations using that stream are considered to be null operationsthat is, they have no effect at all. Unfortunately for us, the computer does not halt the program or give any error message. The computer just continues executing the program, silently ignoring each additional attempt to use that stream. |
|
|
|
|
|
|
|
|
Invalid data is the most common reason for input failure. When your program inputs an int value, it is expecting to find only digits in the input stream, possibly preceded by a plus or minus sign. If there is a decimal point somewhere within the digits, does the input operation fail? Not necessarily; it depends on where the reading marker is. Let's look at an example. |
|
|
|
|
|
|
|
|
Assume that a program has int variables i, j, and k, whose contents are currently 10, 20, and 30, respectively. The program now executes the following two statements: |
|
|
|
|
|
|
|
|
cin >> i >> j >> k;
cout << i: << i << j: << j << k: << k; |
|
|
|
|
|
|
|
|
If we type these characters for the input data: |
|
|
|
|
|
|
|
|
then the program produces this output: |
|
|
|
|
|
|
|
|
Remember that when reading int or float data, the extraction operator >> stops reading at the first character that is inappropriate for the data type (whitespace or otherwise). In our example, the input operation for i succeeds. The computer extracts the first four characters from the input stream and stores the integer value 1234 into i. The reading marker is now on the decimal point: |
|
|
|
|
|