Consider the following code:
# Include <iostream>
Using namespace std;
Int main ()
{
Int;
While (cout <"input a integer (1-10):", cin> ,! (A> = 1 & a <= 10 ))
Cout <"try again! "<Endl;
Return 0;
}
The intention is to allow the user to select a number ranging from 1 to 10. If it is not a number ranging from 1 to 10, re-enter it.
Analysis:
If the user inputs an int not greater than 1-10, the program runs correctly and prompts the user to re-enter it.
However, if the user mistakenly inputs a character char, the result is that the while loop is always executed!
Error analysis:
When cin attempts to read the entered characters as int Data fails, an error occurs-cin. fail (). however, if you want to use cin to read data from the input stream, the input stream must be in the error-free state. Therefore, because the error status exists, the while loop is always executed.
Error Correction:
# Include <iostream>
Using namespace std;
Int main ()
{
Int;
While (cout <"input a integer (1-10):", cin> ,! (A> = 1 & a <= 10) | cin. fail ())
{
Cout <"try again! "<Endl;
Cin. clear (); // clear the error status of std: cin
Cin. sync (); // clear the input buffer
}
Return 0;
}
Add the cin. fail () that determines whether the input is successful and the cin. clear () and cin. sync () that corrected the incorrect input ();
Std: cin. sync (); this sentence is indispensable, because all data input from the standard input device is saved in the buffer first, and then the istream object is extracted from the buffer. If you do not clear the cache, the next time you read the data, an error will occur again and an endless loop will occur.