忽略要从中选择的内容之外的用户输入
我有一个程序,用户必须通过输入数字1-5进行选择。我如何处理他们输入这些边界之外的数字或甚至是字符时可能产生的任何错误?
I have a program in which the user must make a selection by entering a number 1-5. How would I handle any errors that might arise from them entering in a digit outside of those bounds or even a character?
编辑:对不起,我忘了提及这将是C ++
Sorry I forgot to mention this would be in C++
注意这一点。如果用户输入一个字母,以下将产生一个无限循环:
Be careful with this. The following will produce an infinite loop if the user enters a letter:
int main(int argc, char* argv[])
{
int i=0;
do {
std::cout << "Input a number, 1-5: ";
std::cin >> i;
} while (i <1 || i > 5);
return 0;
}
问题是 std :: cin> > i
将不从输入流中删除任何内容,除非它是一个数字。所以当它循环并且第二次调用 std :: cin>> i
时,它读取与以前相同的东西,从不给用户一个机会输入任何东西有用。
The issue is that std::cin >> i
will not remove anything from the input stream, unless it's a number. So when it loops around and calls std::cin>>i
a second time, it reads the same thing as before, and never gives the user a chance to enter anything useful.
因此,更安全的做法是首先读取字符串,然后检查数字输入:
So the safer bet is to read a string first, and then check for numeric input:
int main(int argc, char* argv[])
{
int i=0;
std::string s;
do {
std::cout << "Input a number, 1-5: ";
std::cin >> s;
i = atoi(s.c_str());
} while (i <1 || i > 5);
return 0;
}
你可能想使用比 atoi
虽然。