Link to home
Start Free TrialLog in
Avatar of dsteers
dsteers

asked on

How to make a Switch Exit

A Switch.

How do I make it that if someone enters anything else other that an integer (1,2,3 or 4) into this switch, that the program then displays a message "Try again" and then displays the menu over again for them to choose from.

At the moment whenever I enter an non integer value it loops constantly, with the default value displaying.

int chioce;
   do
   {
     cin >> choice;

      switch (choice)
      {
         case 1:
           flag=true;
           break;
         case 2:
           flag=true;
           break;
         case 3:
           flag=true;
           break;
         case 4:
           flag=true;
           break
         default:
            cout << "Not a Valid Choice" << endl;
    }while (flag !=true);

Thanks
ASKER CERTIFIED SOLUTION
Avatar of Zoppo
Zoppo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
default:
  cout << "Not a Valid Choice" << endl;
  cin.clear ();
  cin.ignore (INT_MAX, '\n');


for INT_MAX include limits.h
Avatar of snoegler
snoegler

Where do you set 'flag' to false?

int chioce;
  do
  {
    cin >> choice;
    flag = false; // <-- i miss this here

     switch (choice)
     {
        case 1:
          flag=true;
          break;
        case 2:
          flag=true;
          break;
        case 3:
          flag=true;
          break;
        case 4:
          flag=true;
          break
        default:
           cout << "Not a Valid Choice" << endl;
   }while (flag !=true);
Avatar of dsteers

ASKER

Thanks Zoppo :-)
You're welcome,

have a nice day,

regards,

ZOPPO