带菜单的输入验证 C++

input validation c++ with menu

我有这样的菜单。

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() 但不确定如何实施

如果可以将该 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 choiceInt = choice - '0';

首先将一个字符串作为输入,然后尝试将其转换为 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;
}

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

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

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

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%