【发布时间】:2016-05-27 01:28:22
【问题描述】:
我目前正在做一个小项目来学习(和娱乐)并且需要while-loop 来检查用户的输入是否是整数 1、2、3、4 或 5 之一。什么是最好的方法是什么?这是我在代码中的基本想法,但它并不完全有效:
std::cin >> input;
while (cin.fail() == true || input != 1 && input != 2 && input != 3 && input != 4 && input != 5){
std::cout << std::endl "The valid choices are 1, 2, 3, 4, and 5. Please choose: ";
std::cin >> input;
std::cout << std::endl;
}
这仅适用于大于 5 的数字,但如果我输入字母则失败。如何使用cin.fail() 正确验证?
【问题讨论】:
-
必须是for循环吗?
-
哎呀,意思是说while循环。谢谢你抓住那个。现在改变它。
-
另外它失败的原因是因为输入可能是一个 int ,而你正在输入一个字符。这是非常合乎逻辑的行为。
-
我确实希望 cin 失败,但是我需要失败来触发 while 循环再次询问新的输入。
标签: c++ validation input while-loop