How can I check if a user's input is both valid and also a number I'm looking for?

2830 views c++
2

How could I create a conditional statement that prevents entering the fail state, and asks the user for new data when either the data is invalid or the data is not 1, 2, 3 OR 4 ?

int choice;

while ( !choice || choice != 1 || 2 || 3 || 4){
     cout << "Entry Invalid. Enter again: ";
     cin >> choice
}

For example, If the user enters 'f', then the fail state would be taken care of, and the program would ask for new data. And when they enter 5, the program would say "Not a valid number", and ask for new data.

answered question

Read input as a character (or string - a set of characters). If that succeeds, check if it represents valid input (e.g. a set of digits). Get out of the habit of from trying to check multiple values using construct like choice != 1 || 2 || 3 || 4 because that does not do anything like what you seek - read any basic textbook on C++ to understand both what that construct does and what you actually need to do.

1 Answer

9

For stoi you need C++11 standard

int choice;
string inp;

cin >> inp;

while(inp != "1" && inp != "2" && inp !="3" && inp !="4"){

    cout << "Wrong input , type again" << endl;
    //system("PAUSE");
    cin >> inp;

}
choice = stoi(inp);
cout << choice;

posted this

Have an answer?

JD

Please login first before posting an answer.