【问题标题】:input validation c++ with menu带菜单的输入验证 C++
【发布时间】:2016-12-19 10:59:22
【问题描述】:

我有这样的菜单。

int choice;
cout <<"1: Exit\n2: Print Mark\n3: Print Name"<<endl;
cin >> choice;

while (choice != 1 && choice != 2 && choice != 3)
   {
     cout << "Invalid Choice <<endl;
     cout <<"1: Exit\n2: Print Mark\n3: Print Name"<<endl;
     cin >> choice;
   }

这就是我目前所拥有的,但是当我输入字母时它会终止,是否有一种更简单的方法来测试无效输入。 我知道有类似 cin.fail() 但不确定如何实现它

【问题讨论】:

  • 你应该做while (choice != '1' &amp;&amp; choice != '2' &amp;&amp; choice != '3'),对吧?
  • 我刚刚给一个类似的问题写了this answer。检查其中的代码,尤其是我将std::cin &gt;&gt; ... 置于条件中的prt。
  • @Nishant 不,因为 OP 正在读取 整数

标签: c++ validation input while-loop cin


【解决方案1】:

好的,你可以像这样构造你的代码

do {
     if (choice ==1)
     {
       exit(1);
     }else if (choice==2)
     {
      //code 
     }
     }else if (choice==3)
      {
        //code
      }
      }else if (choice==4)
      {
        //code
       }else{
             cout <<"Please enter a correct option"<<endl;
             cin.clear();
             string choice;
             cin>>choice;
            }
}while(!cin.fail())

这 100% 有效

【讨论】:

    【解决方案2】:

    当输入错误时,这个简单的行跳过。

    td::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignore and skip bad input
    

    【讨论】:

      【解决方案3】:

      首先将一个字符串作为输入,然后尝试将其转换为 int 以查看它是否有效。你可以这样(如果使用 c++11):

      #include <iostream>
      #include <cstring>
      
      using namespace std;
      
      int main() {
          int choice = -1;
          while (true) {
              string input;
              cout << "1: Exit\n2: Print Mark\n3: Print Name" << endl;
              cin >> input;
              try {
                  choice = stoi(input);
                  if (choice > 0 && choice < 4) {
                      break;
                  }
              } catch (const std::exception& e) {
              }
              cout << "Invalid input" << endl;
          }
      
          cout << "Your valid choice: " << choice << endl;
      }
      

      【讨论】:

        【解决方案4】:

        如果可以将该 int 更改为 char,您可以这样做。 这样很容易。

        char choice;
        cout <<"1: Exit\n2: Print Mark\n3: Print Name"<<endl;
        cin >> choice;
        
        while (choice != '1' && choice != '2' && choice != '3')
           {
             cout << "Invalid Choice <<endl;
             cout <<"1: Exit\n2: Print Mark\n3: Print Name"<<endl;
             cin >> choice;
           }
        

        如果您想将选择返回为 int,您可以这样做

        int choiceInt = choice - '0';
        

        【讨论】:

        • 这是否也会像我输入'ASDA'一样验证?
        • 使用字符并不稳定。很多时候它会得到'\n',而不是你想要的字符或其他不可见的字符。
        猜你喜欢
        • 1970-01-01
        • 2013-01-01
        • 2014-10-29
        • 2017-04-09
        • 2015-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多