简体   繁体   中英

While Loop Repeats 4 Times

I'm trying to only accept integers as input and loop through it at the same time as a sort of validation. The problem is, when a user enters something along the lines of "Two" the while loop goes through the input 3 different times before asking the user again. Is there a way to prevent this from happening and just skip the 3 iterations?

cout << "Enter Student ID: ";
while(!(cin >> id))
{
    cout << "\nERROR: Please enter a Positive Whole Number" << endl;
    cin.clear();
    cin.ignore ();
    cout << "Enter Student ID: ";
}

You can use this.

cin.ignore (std::numeric_limits<streamsize>::max (), '\n') ;

It would skip all the lines and you wont get extra loop iterations, no matter how many invalid characters you enter.

The reason for your while loop iterating is that the stream is not being extracted completely so by just using this line

cin.ignore (std::numeric_limits<streamsize>::max (), '\n') ;  

the loop will iterate only for once because no matter how much big input you give it will be extracted. Cin.ignore() only removes the one character from the stream.

In your case if you enter "two" then after firs iteration only 't' will be extracted and the input would be "wo" for the second iteration. But by adding this line stream would be empty in the second iteration and will take input from user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM