忽略要选择的内容之外的用户输入
我有一个程序,用户必须通过输入数字 1-5 来进行选择。我将如何处理由于输入超出这些范围的数字甚至字符而可能出现的任何错误?
编辑:抱歉我忘了提到这将是用 C++ 编写的
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++
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对此要小心。如果用户输入字母,以下内容将产生无限循环:
问题是
std::cin >>>我
不会从输入流中删除任何内容,除非它是一个数字。因此,当它循环并第二次调用std::cin>>i
时,它会读取与之前相同的内容,并且永远不会让用户有机会输入任何有用的内容。因此,更安全的选择是首先读取字符串,然后检查数字输入:
不过,您可能希望使用比 atoi 更安全的东西。
Be careful with this. The following will produce an infinite loop if the user enters a letter:
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 callsstd::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:
You'll probably want to use something safer than
atoi
though.