Ignore user input outside of what's to be chosen from

你说的曾经没有我的故事 提交于 2019-12-12 10:17:12

问题


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?

Edit: Sorry I forgot to mention this would be in C++


回答1:


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;
}

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;
}

You'll probably want to use something safer than atoi though.



来源:https://stackoverflow.com/questions/4975711/ignore-user-input-outside-of-whats-to-be-chosen-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!