1

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

4 Answers4

3

This simple line skip when it's a bad input.

td::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignore and skip bad input
Lord_Curdin
  • 957
  • 1
  • 14
  • 27
0

If it is possible for changing that int to char you can do like this. Its easy this way.

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

If you want to get the choice back as int, you can do

int choiceInt = choice - '0';
javaDeveloper
  • 1,403
  • 3
  • 28
  • 42
  • will this also validate like if i input 'ASDA' ? –  Aug 12 '16 at 12:28
  • Working with chars is not stable at all. Many times it will get `'\n'` instead of the char you want or other invisible characters. – Fma Aug 12 '16 at 12:30
0

First take a string as input then try to cast it to int to see if it is valid. You can make it like this (if using 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;
}
Fma
  • 362
  • 1
  • 11
0

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%

kunz
  • 1,063
  • 1
  • 11
  • 27