When cin fails to be read, does it enter an endless loop? -Analyze input stream conditions

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.