C++ 如果我输入的是字母而不是数字,为什么会出现无限循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19521320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why do I get an infinite loop if I enter a letter rather than a number?
提问by user2907563
I am writing this code for a homework assignment (just starting C++ so please go easy). We've just started while, do-while, and for loops today. The program runs fine except that if you enter a letter when the program asks for an integer, it loops infinitely. What is going on? (Code below) ***EDIT: To clarify, the part that is looping is: "The number you have entered is negative. Please enter a positive number to continue." But the user is not given a chance to enter another number. It just keeps printing this.
我正在为家庭作业编写这段代码(刚开始使用 C++,所以请放轻松)。今天我们刚刚开始使用 while、do-while 和 for 循环。该程序运行良好,但如果您在程序要求输入整数时输入一个字母,它会无限循环。到底是怎么回事?(下面的代码)***编辑:澄清一下,循环的部分是:“您输入的数字是负数。请输入正数以继续。” 但是用户没有机会输入另一个号码。它只是不断地打印这个。
#include <iostream>
using namespace std;
int main ( )
{
//define variables
int num1, num2, total;
char answer1;
do
{
//user enters a number
cout << "\nPlease enter a positive number and press Enter: \n";
cin >> num1;
//check that the given num1 value is positive
while (num1 < 0)
{
cout << "The number you entered is negative.\nPlease enter a positive number to continue.\n";
cin >> num1;
}
cout << endl;
//add the sum of 1 through num1 value
num2 = 1;
total = 0;
while (num1 >= num2)
{
total = total + num2;
num2 ++;
}
//tell the user the sum
cout << "The total of all the integers\nfrom 1 to " << num1 << " is: \n";
cout << total;
//ask if the user wants to try again
cout << "\n\nWould you like to try again with a new number?\nEnter y for yes or n for no.\n";
cin >> answer1;
} while (answer1 == 'y');
cout << endl;
return 0;
}
回答by Sergey
This is how basic_istream
works. In your case when cin >> num1
gets wrong input - failbit
is set and cin
is not cleared. So next time it will be the same wrong input. To handle this correctly you can add check for correct input and clear&ignore cin
in case of wrong input. For example:
这就是basic_istream
工作原理。在您cin >> num1
输入错误的情况下-failbit
已设置cin
且未清除。所以下次它会是同样的错误输入。要正确处理此问题,您可以添加检查正确输入并清除并忽略cin
错误输入。例如:
#include<limits>
//user enters a number
cout << "\nPlease enter a positive number and press Enter: \n";
do {
while(!(cin >> num1)) {
cout << "Incorrect input. Please try again.\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
if(num1 < 0) cout << "The number you entered is negative. Please enter a positive number to continue.\n";
} while(num1 < 0);
回答by Axel
When you enter a letter, the error state of cin
is set and there won't be any further input possible before you call cin.clear()
. In consequence, the statement cin >> num1
will not change the value of num1
and you loop forever.
当您输入一个字母时,将cin
设置错误状态并且在您调用 之前不会有任何进一步的输入可能cin.clear()
。因此,该语句cin >> num1
不会更改 的值num1
并且您将永远循环。
Try this:
尝试这个:
while (num1 < 0)
{
cout << "The number you entered is negative.\nPlease enter a positive number to continue.\n";
cin.clear();
cin >> num1;
}
EDIT:
编辑:
Thanks to Lightness for pointing this out. You should initialize num1
too:
感谢 Lightness 指出这一点。你也应该初始化num1
:
int num1=-1, num2, total;
回答by ghembo
This answershould solve your problem. Basically you are trying to read a character from the stream and it can't be parsed to an int, so the stream is left in an error state.
这个答案应该可以解决您的问题。基本上,您正在尝试从流中读取一个字符,但它无法解析为 int,因此流处于错误状态。
You should check for an error, clear it and react accordingly.
您应该检查错误,将其清除并做出相应的反应。
回答by Al-Hanash Moataz
You can use a "char" datatype as an input from the user then use "static_cast("variable name");
您可以使用“char”数据类型作为用户的输入,然后使用“static_cast("variable name");
char input;
int choose;
cin >> input;
choose = static_cast<int>(choose) - 48;///then use 'if' statement with the variable 'choose'