I was wondering if there is a way to make it so that someone can only input a specific data type.

My program ask for input of specific numbers for a menu. If I enter a character, the program crashes.

Is there a way to make it so that it the user is forced to enter an integer?

Here is a piece of the code that could use this. Cant copy the entire program as it is over 600 lines long.

do
                                       {
                                           record[x].setAssignments();
                                           record[x].setGrades();
                                           
                                           
                                           do
                                           {
                                               cout<<"\n\n\n|:1:|  Enter Another Grade\n";
                                               cout<<"|:2:|  Exit\n";
                                               cin>>y;
                                               if(y!=1||y!=2)
                                               {
                                                         cout<<"Invalid Answer...";
                                                         pause();
                                                         clear();
                                           
                                               }
                                           }while(y!=1||y!=2);
                                       }while(y==1);

Edited 4 Years Ago by rjstamey: n/a

if you want to only get an integer then you could use something like this

cout << "Enter menu number: "
cin >> number;
while (cin.fail())
{
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n') // need to #include<limits> for this
    cout << "Please enter a valid number: "
    cin >> number;
}

If you want to make something more robust than you could always take the input in as a string and then try a conversion to the type you want.

Take all inputs as a character string. Then test the characters to make sure they fit your required input. If not, display an error; if so, convert to integer and continue.

This article has been dead for over six months. Start a new discussion instead.