【问题标题】:Input Validation Inside While LoopWhile循环内的输入验证
【发布时间】: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


【解决方案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

【讨论】:

    【解决方案2】:

    假设输入是一个整数,当它读入一个字符串/字符时会发生故障。你需要的是

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-05-13
      • 2015-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-08
      • 2018-04-16
      • 2015-05-05
      相关资源
      最近更新 更多