C++ 输入验证c++;带菜单

C++ 输入验证c++;带菜单,c++,validation,input,while-loop,cin,C++,Validation,Input,While Loop,Cin,我有这样的菜单 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:

我有这样的菜单

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;
   }
int选择;

cout如果可以将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,以查看它是否有效。您可以这样做(如果使用c++11):

#包括
#包括
使用名称空间std;
int main(){
int-choice=-1;
while(true){
字符串输入;
不能输入;
试一试{
选择=stoi(输入);
如果(选项>0&&选项<4){
打破
}
}捕获(const std::exception&e){
}

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

td::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignore and skip bad input
td::cin.ignore(std::numeric_limits::max(),'\n');//忽略并跳过错误输入

好的,您可以这样构造代码

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())
do{
如果(选项==1)
{
出口(1);
}else if(选项==2)
{
//代码
}
}else if(选项==3)
{
//代码
}
}else if(选项==4)
{
//代码
}否则{

你能在(选择!='1'和&choice!='2'和&choice!='3'时做
while吗
,对吗?我刚刚写了一个类似的问题。检查其中的代码,特别是我把
std::cin>>…
放在一个条件中的prt。@Nishant否,因为OP正在读取整数。这是否也会像输入“ASDA”一样进行验证?使用字符根本不稳定。很多时候,它会得到
'\n'
,而不是您需要的字符想要或其他看不见的字符。
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())