带有菜单的c++输入验证

input validation c++ with menu

本文关键字:输入 验证 c++ 菜单      更新时间:2023-10-16

我的菜单是这样的

int choice;
cout <<"1: Exitn2: Print Markn3: Print Name"<<endl;
cin >> choice;
while (choice != 1 && choice != 2 && choice != 3)
   {
     cout << "Invalid Choice <<endl;
     cout <<"1: Exitn2: Print Markn3: Print Name"<<endl;
     cin >> choice;
   }

,这就是我到目前为止所拥有的,但是当我输入字母时,它终止了,有没有一种更简单的方法来测试无效输入。我知道有一种东西叫"失败"。但不确定如何实现

这个简单的行跳转当它是一个不好的输入

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())

如果可以将整型转换为char,可以这样做。这样很容易。

char choice;
cout <<"1: Exitn2: Print Markn3: Print Name"<<endl;
cin >> choice;
while (choice != '1' && choice != '2' && choice != '3')
   {
     cout << "Invalid Choice <<endl;
     cout <<"1: Exitn2: Print Markn3: 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: Exitn2: Print Markn3: 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;
}