我只是编程新手,我试图编写一个 while 循环,只要输入 (num
) 不是不以零结尾的整数,它就会运行。当我输入一个以零结尾的数字时,程序会正确运行循环,但是当我输入一些无意义的东西时,比如 rofl
,程序只会打印 The input is not valid.
并且不会重复循环。我试图寻找解决方案,但一个小时后我仍然卡住了。任何人都可以在这里帮助我吗?非常感谢!
void rev_sum() {
int num;
int a = 1;
while (a < 2) {
cout << "Please input a natural number without zero at the end:\n";
cin >> num;
if (!cin) {
cout << "The input is not valid.\n";
cin.clear();
cin.ignore(INT_MAX);
}
if (num % 10 == 0) {
cout << "The number cannot have zero at the end\n";
} else {
cout << "gj\n";
break;
}
}
}
最佳答案
尝试替换
cin.ignore(INT_MAX);
与
cin.ignore(numeric_limits<streamsize>::max(), '\n');
并改变
if (num % 10 == 0)
到
else if (num % 10 == 0)
您的最终代码应如下所示:
void rev_sum() {
int num;
int a = 1;
while (a < 2) {
cout << "Please input a natural number without zero at the end:\n";
cin >> num;
if (!cin) {
cout << "The input is not valid.\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
else if (num % 10 == 0) {
cout << "The number cannot have zero at the end\n";
} else {
cout << "gj\n";
break;
}
}
}
关于c++ - 为什么我在 C++ 中的 while 循环不能正确运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26047714/