忽略要从中选择的内容之外的用户输入 [英] Ignore user input outside of what's to be chosen from

查看:190
本文介绍了忽略要从中选择的内容之外的用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,用户必须通过输入数字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 虽然。

这篇关于忽略要从中选择的内容之外的用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆