checking for alpha numeric in user input

hey guys there is yet another problem im having now i know how to check for characters in user input the problem was that if the user entered a alpha numeric number the code did not catch it and lets the user pass.

now i managed to stop that from hapening but now it doesnt let any value pass through.

here is the code for it.

1
2
3
4
5
6
7
8
9
int userDecision; // This variable will store the users decision.
cout << "What kind of trip would you like?\n" << "Enter '1' for a round-trip or '2' for a one-way trip: ";
cin >> userDecision;
while(cin.fail() || userDecision != 1 || userDecision != 2){ // This while loop checks if what the user entered is char,alpha or any other invalid value other than 1 or 2.
      cout << "\n\n" << "Invalid Entry!\n" << "You can only enter '1' or '2': ";
      cin.clear();
      cin.ignore(numeric_limits<streamsize>::max(), '\n');
      cin >> userDecision;
}


now even if i enter 1 or 2 the while loop wont let me pass i cant seem to figure out whats wrong...
Last edited on
userDecision != 1 || userDecision != 2 is always true

Replace
while(cin.fail() || userDecision != 1 || userDecision != 2) {

With
while( cin.fail() || ( userDecision != 1 && userDecision != 2) ) {

lol looks like i missed that. At the time it somehow seemed right lol. thanks for the help.
Just one problem tho im back where i started. now if the user enters a alphanumeric that contains either 1 or 2 for example "1asdwas" or "2asdwa". the while loop lets it pass when it should not.

If any other alphanumeric is entered other than a one that contains 1 or 2 the code catches it and displays an error message but not with the one that contains either 1 or 2.

any hints on how to solve that problem?
Last edited on
Read the input as a string, validate that the the entire string is a valid number. If it is, convert the string to an int (use std::istringstream for this).

For example:
1
2
3
4
5
6
7
8
9
10
11
    int number ;
    std::string input ;
    while( std::cout << "number? (1-99): " && std::cin >> input )
    {
        std::istringstream stm(input) ;
        if( stm >> number // a number was read
            && stm.eof() // the entire string was consumed
            && ( number >= 1 || number <= 99 ) // the number entered is valid
           ) break ;
    }
    // use number  

Last edited on
Topic archived. No new replies allowed.