无效的 int 输入卡在无限循环中
invalid int input gets stuck in an infinite loop
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');
}
相关文章:
- 在这个无限循环中,当输入 0 时终止,当输入 int 范围之外的任何内容时,程序行为不正常
- 陷入输入C++的无限循环中
- 字母输入运行无限循环
- 为什么输入流无法识别 Ctrl D 并给出无限循环
- 开关大小写语句中函数中的字符串输入会导致无限循环和绕过输入
- 实现递归函数,避免由 C++ 中 include 的循环调用(没有 #pragma 一次)引起的无限循环输入
- 为什么当用户输入除整数之外的任何内容时,我的程序会无限循环输出?C++
- 输入 2 个非常基本的 C 字符串时的无限循环
- C++ 输入字符而不是 int 会导致无限循环.如何检查错误的输入
- 如何在 c++ 中从".in"格式的文件中获取输入?此代码进入无限循环,但适用于".txt"文件格式
- 为什么我的程序在输入字符时有一个无限循环
- 输入验证,需要数字,而不是字符串.代码导致无限循环
- 在等待输入时执行无限循环
- Getline 在将文件重定向到标准输入时会导致无限循环
- 检查正确的输入会导致无限循环
- 如果给出错误的输入,则无限循环
- 读取输入文件时的无限循环
- C++用户输入到字符串数组的无限循环
- 无效的 int 输入卡在无限循环中
- 无限循环,同时在 STACK 中输入不同的数据类型值