如何在C ++中正确使用cin.fail() [英] How to use cin.fail() in c++ properly
问题描述
我正在编写一个程序,使用 cin>> iUserSel;
从用户那里获得整数输入。如果用户输入字母,程序将进入无限循环。我试图通过下面的代码来防止这种情况,但是程序进入无限循环并打印出错误!输入#!。我该如何修复程序?
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
我在使用cin.fail()和 C ++ cin.fail()问题
,但我不知道如何使用它们来解决我的问题。
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.
推荐答案
当 cin
失败时,您需要清除错误标志。否则后续的输入操作将是非操作。
When cin
fails, you need to clear the error flag. Otherwise subsequent input operations will be a non op.
要清除错误标志,您需要调用 cin.clear()
。
To clear the error flags, you need to call cin.clear()
.
您的代码将变为:
cin >> iUserSel;
while (iValid == 1)
{
if (cin.fail())
{
cin.clear(); // clears error flags
cin.ignore();
cout << "Wrong! Enter a #!" << endl;
cin >> iUserSel;
}//closes if
else
iValid = 0;
}//closes while
我也建议您更改
cin.ignore();
至
cin.ignore(numeric_limits<streamsize>::max(), '\n');
如果用户输入多个字母。
In case the user enters more than one letter.
这篇关于如何在C ++中正确使用cin.fail()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!