c-无效的int输入陷入无限循环
作者:互联网
这个问题已经在这里有了答案: > Infinite loop with cin when typing string while a number is expected 4个
do
{
cout << "Enter the numerator and denominator of the first fraction: ";
cin >> a >> b;
cout << endl;
cout << "Enter the numerator and denominator of the second fraction: ";
cin >> c >> d;
cout << endl;
} while (!validNum(a, b, c, d));
...
bool validNum(int num1, int num2, int num3, int num4)
{
if (cin.fail() || num2 == 0 || num4 == 0)
{
if (num2 == 0 || num4 == 0)
{
cout << "Invalid Denominator. Cannot divide by 0" << endl;
cout << "try again: " << endl;
return false;
}
else
{
cout << "Did not enter a proper number" << endl;
cout << "try again: " << endl;
return false;
}
}
else
return true;
}
我要尝试做的是确保分母不为零,并且仅输入数字.除零代码可以正常工作,但是当您输入一个char值时,它将进入一个无限循环,并且不知道为什么.有任何想法吗?
解决方法:
if (cin.fail() ... )
输入无效值(即char)后,流中的故障位将打开,validNum将始终返回false,从而导致无限循环.
您需要清除错误状态,并在每次调用后忽略其余输入:
if (std::cin.fail())
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
标签:c,infinite-loop 来源: https://codeday.me/bug/20191009/1878521.html