I'm writing a program where I get an integer input from the user with cin>>iUserSel;
. If the user puts in a letter, the program goes to an infinite loop. I tried to prevent that with the code below, but the program goes to an infinite loop and prints out "Wrong! Enter a #!". How can I fix my program?
cin>>iUserSel;
while (iValid == 1)
{
if (cin.fail())
{
cin.ignore();
cout<<"Wrong! Enter a #!"<<endl;
cin>>iUserSel;
}//closes if
else
iValid = 0;
}//closes while
I found some information on this at Correct way to use cin.fail() and C++ cin.fail() question , but I didn't understand how to use them to fix my issue.
question from:https://stackoverflow.com/questions/66065948/is-cin-fail-with-my-while-loop-causing-my-output-to-infinitely-loop