C++ 修复无意的无限循环
当我输入一个像63453462这样的随机数时,它的响应是“无效数”,但在一个无限循环中,但如果我输入一个像2000002这样的数字,它只会说没有循环的无效数。我需要帮助,当有人插入像2145345665465这样的随机数时,不要进行无限循环C++ 修复无意的无限循环,c++,C++,当我输入一个像63453462这样的随机数时,它的响应是“无效数”,但在一个无限循环中,但如果我输入一个像2000002这样的数字,它只会说没有循环的无效数。我需要帮助,当有人插入像2145345665465这样的随机数时,不要进行无限循环 #include <iostream> using namespace std; int main () { int sum , input , number; cout << "Enter
#include <iostream>
using namespace std;
int main ()
{
int sum , input , number;
cout << "Enter any positive integer that is less than or " ;
cout << "equal to 2,000,000 to determine if it is divisible by 11.";
cout << endl;
cout << "If the number is greater than 99, we use Dodgsons's rule";
cout << endl;
cout << "which determines if it is a factor or not.\n";
cout << endl;
cin >> input;
while ((input < 1) || ( input > 2000000 ))
{
cout << "Invalid number detected, please enter a positive integer.\n";
cin >> input;
}
number = input;
while ((input>=100) && (input < 2000000))
{
sum = input % 10;
input = input /10 - sum;
cout << input << endl;
}
if (input % 11 == 0)
cout << "the number is divisible by 11." << endl;
else
cout << "the number is not divisible by 11." << endl;
system ("Pause");
return 0;
}
#包括
使用名称空间std;
int main()
{
整数和,输入,数字;
coutwhile((输入<1)| |(输入>2000000))
{
cout>输入;
cin.clear();
}
cin.clear()
将清除导致无限循环的任何先前状态。您需要正确检查输入操作是否成功。如果您输入了无法解析为整数的内容,或者输入了大于或小于INT\u MAX
的值,则在
cin >> input
流std::cin
将进入失败状态,这意味着设置了failbit
。此后,除非您注意,否则以下每个输入操作也将失败
通常的方法是清除输入缓冲区(无法处理的输入),然后重试:
while (not (cin >> input) or not is_valid(input)) {
cout << "Invalid input, try again" << endl;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cin.clear();
}
在这里是无用的,您可以直接读入number
(名称更合适)并将变量input
放在一起。那么,您是否使用调试器逐行检查了此变量?cin
可能进入失败
状态,导致后续每个输入操作失败,直到问题出现(不是数字,数字太大,…)已解决(通常通过清除输入缓冲区)。是否有理由收回upvote?如果缺少或错误,请告诉我。
while (not (cin >> input) or not is_valid(input)) {
cout << "Invalid input, try again" << endl;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cin.clear();
}
number = input;