Home > front end >  How do validate if user inputs anything other than a character?
How do validate if user inputs anything other than a character?

Time:10-28

I have a function that asks if the user wants to return to the main menu.

void menuReturn() {
    char cont;
    do {
        cout << "Return to Main Menu? [Y/N]: ";
        cin >> cont;
        cont = toupper(cont);
        if (cont == 'Y') {
            system("cls");
            break;
        }
        else if (cont == 'N') { 
            cout << "Closing program...";
            exit(0);    
        }
        else {
            cout << "Invalid choice" << endl;
        }        
    } while (cont !=  'Y'|| cont != 'N');
}

But when the user inputs a string or an integer higher than nine (9), the console shows this:

Return to Main Menu? [Y/N]: apple
Invalid choice
Return to Main Menu? [Y/N]: Invalid choice
Return to Main Menu? [Y/N]: Invalid choice
Return to Main Menu? [Y/N]: Invalid choice
Return to Main Menu? [Y/N]: Invalid choice
Return to Main Menu? [Y/N]: 

How do I get rid of the redundant return to menu messages? How do I make it look like this instead?

Return to Main Menu? [Y/N]: apple
Invalid choice
Return to Main Menu? [Y/N]:

CodePudding user response:

Collect the input as a string, then check if it has only one character or not using string.length(), If it is one character convert it to char. You can convert it using strcopy method or just

char character = string[0];

I'm not sure if the above one works, but try it. Hope it helped! Also use std::getline(std::cin, string) instead of std::cin if you want to input spaces in console!

CodePudding user response:

Whats happening here is that char can only hold one character, but apple takes up 5 characters.

At each iteration of the loop, std::cin reads only 1 character at a time from the console (that you have already entered). Putting the print statement std::cout << "Read: " << cont; illustrates this by the below output:

Return to Main Menu? [Y/N] apple
Read: a
Return to Main Menu? [Y/N] Read: pInvalid Choice
Return to Main Menu? [Y/N] Read: pInvalid Choice
Return to Main Menu? [Y/N] Read: lInvalid Choice
Return to Main Menu? [Y/N] Read: eInvalid Choice

To fix this, either use a std::string and std::getline, and make sure to validate the entered length is 1.

  • Related