输入验证内部循环

时间:2016-02-15 23:45:37

标签: c++ validation input while-loop

我目前正在开发一个小项目来学习(并且为了好玩)并且需要<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p class="collapsible collapsed">I want to show just the first line of a block of wrapped text, and then reveal the whole block on click. Also, I'd like to know how to toggle it back to the compact one-line version on a second click. Is there an easy way to do this through css + javascript? I use jQuery.</p> <p class="collapsible">I want to show just the first line of a block of wrapped text, and then reveal the whole block on click. Also, I'd like to know how to toggle it back to the compact one-line version on a second click. Is there an easy way to do this through css + javascript? I use jQuery.</p> <p class="collapsible collapsed">I want to show just the first line of a block of wrapped text, and then reveal the whole block on click. Also, I'd like to know how to toggle it back to the compact one-line version on a second click. Is there an easy way to do this through css + javascript? I use jQuery.</p>来检查用户的输入是否是整数1,2,3之一, 4,或5.最好的方法是什么?这是我在代码中的基本想法,但它并不是很有效:

while-loop

这只有在数字大于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; } 正确验证?

2 个答案:

答案 0 :(得分:1)

假设输入是整数,则在读取字符串/ char时会发生失败。你需要的是

cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');

在你的while循环体中,因为当它失败时,流关闭,所以你需要清除它。

为了扩展一点,cin.clear()只清除流,然后在cin.ignore()中忽略该行的其余部分。它将忽略最大可能的行大小,因此它是最正确的,但是大多数程序可以通过在那里放入一些巨大的数字而逃脱。

答案 1 :(得分:1)

首先

#include <limits> 

获取最大流量化。然后翻转一些逻辑

while (!std::cin >> input ||  // didn't read valid input
       input < 1 || // number too small
       input > 5) // number too large
{
    std::cout << std::endl "The valid choices are 1, 2, 3, 4, and 5. Please choose: ";

然后清除流错误和用户输入的任何其他废话

std::cin.clear();
std::cin.ignore(std::numeric_limits<streamsize>::max(), '\n');

最后要求重做

    std::cin >> input;
    std::cout << std::endl;
}

这不会发生什么:

1.23

cin将停止在'.'读取,因为它未在整数中找到,并且很高兴地返回1.哎呀。

1a

同样的问题

1 holy bad input, Batman!

类似的问题。 cin停在该处。

你真正想要做的是得到whole input line from the user with std::getline,然后使用std::stoi to make sure that it is all an int