c++ - 简单的用户输入验证不起作用

标签 c++ input

我有一个简单的函数,它接受 1 或 2,如果这两个数字都没有输入,则重新提示输入。现在,如果我输入任何数字,它会一直停留在请求有效输入上。我知道这很容易,但我现在看不到。我错过了什么?

#include <iostream>
#include <string>

using namespace std;

int userChoice();

int main()
{
  userChoice();

  return 0;
}

int userChoice()
{
    int input = 0;

    cout << "Enter 1 or 2: ";
    cin >> input;

    while (input != 1 || input != 2 || cin.fail())
    {
        if (cin.fail())
        {
            cin.clear();
            cin.ignore(1000, '\n');
        }

        cout << "Enter only 1 or 2: ";
        cin >> input;
    }

    return input;
}

最佳答案

while 中的条件格式不正确。这将永远是正确的。

你需要使用类似的东西:

while ( !cin || (input != 1 && input != 2) )

策略变更建议

我认为使用递归函数会更好:

int userChoice()
{
   int input = 0;
   cout << "Enter 1 or 2: ";
   cin >> input;

   // If we get a valid input, return.
   if ( cin && (input == 1 || input == 2))
   {
      return input;
   }

   // If there is any error in reading, clear the stream.
   if ( !cin )
   {
      cin.clear();
      cin.ignore(1000, '\n');
   }

   // Call function again.
   return userChoice();
}

关于c++ - 简单的用户输入验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33470671/

相关文章:

c++ - 我如何从输入文件中的数字 "2007"中仅选择数字 "20071406"并将其存储在变量中?

c++ - 在处理序列化时我应该硬编码变量大小吗? C++

PHP 配置文件更新错误 mysql_num_rows

javascript - 电子邮件输入警告 - 组件正在将文本类型的受控输入更改为不受控

python - 文本文件中的分隔符 [0001],在 python 中使用 np.loadtxt 读取

c++ - 使用初始化列表作为值时,插入 std::list<std::vector<int>> 失败?

c++ - 哪个 C++ XSLT 处理器?

php - 如何在mySQL中触发总天数

javascript - 禁用输入字段中的符号和非字母

c++ - 嵌入式 IWebBrowser2 中的 DocumentComplete 事件使用 write() 方法