maandag 18 juni 2007

Numbers reading with CIN and CIN incorrect input

Consider the following code:

int n;
cin >> n;

What happens if the user responds by entering a word instead of a number?
Four things occur in such a mismatch:

- The value of n is left unchanged
- The mismatched input is left in the input queue
- An error flag is set in the cin object
- The call to the cin method, if converted to type bool, returns false.

The fact that the method returns false means that you can use non-numeric input to terminate a number-reading loop. The fact that non-numeric input sets an error flag means that you have to reset the flag before the program can read more input. The clear() method, which also resets the end-of-file (EOF) condition, resets the bad input flag. (Either bad input or the EOF can cause cin to return false.

The expression cin >> fish[i] is really a cin method function call, and the function returns cin. If cin is part of a test condition, it's converted to type bool!
The conversion value is TRUE if input succeeds and FALSE otherwise.


while (!(cin >> golf[i])) {
cin.clear(); // reset input
while (cin.get() != '\n')
continue; // get rid of bad input
cout << "Please enter a number: "; } This is an example of error-handling code with CIN and incorrect input. If cin >> golf[i] results in cin being false, that means the value read was not in the correct format, so for example instead of an int value you enter a word.
Nothing will be stored in the array golf[i]; Then the loop body will be executed., because the condition of cin is FAlSE; In that case, first the stream is reset to a valid condition cin.clear(), that is necesarry to read the inputbuffer, where the word is still stored. Then cin.get() is executed until all characters are removed from the input, even the '\n' because to check for '\n' it is needs to be extracted from the stream.

If the input is correct, a int number in this case, the value is read in golf[i], but the body of the while loop is not executed because the cin object condition is 1 and 1 negated with the ! makes 0 as condition in the while, and while does only execute its body if the condition is true or nonzero.

Geen opmerkingen: