jamesG77296 jamesG77296 - 3 months ago 15
C++ Question

input validation c++ with menu

i have this menu like so.

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;
}


so that is what i have so far but when ever i input letters it terminates is there a easier way to test for invalid inputs.
i know there is something like cin.fail()
but not sure on how to implement it

Answer

okay you can structure your code like this

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

This works 100%