PinkieBarto PinkieBarto - 15 days ago 5
C++ Question

Checking input on a char variable

I'm trying to validate input for a quit/return question in my program so the user is forced to enter either

'r'
or
'q'
.

I have managed to get it almost working. The problem is if the user enters
'r'
or
'q'
at the beginning followed by random letters then the program accepts that input. Any ideas on how to get the program to allow only a single
'r'
or
'q'
?

void exit()
{
char choice;
bool badInput;

do
{
cout << "Press 'r' to return to the menu\nPress 'q' to quit the program\n\n" << endl;
cin >> choice;

badInput = cin.fail();
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
} while (badInput == true && choice == 'r' && choice == 'q' && (cin.peek() == EOF));


if (choice == 'q')
{
system("CLS");
cout << "Bye!\n";
system("PAUSE");
}
else if (choice == 'r')
{
system("CLS");
main();
}
else
{
exit();
}
}

Answer

You've got a very strange way of approaching this problem that's got a lot of issues. In particular, creating a function called exit() is problematic since that's a core function, and calling it recursively to try and get input is likewise not a good plan. You already have a loop, you just need to use it more effectively.

Likewise, main() is called automatically and you should never have reason to call it manually.

Here's a first pass rewrite:

void getInput()
{
    char choice;

    while (true)
    {
        cout << "Press 'r' to return to the menu\nPress 'q' to quit the program\n\n" << endl;

        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');

        cin >> choice;

        switch (choice)
        {
            case 'q':
                system("CLS");
                cout << "Bye!\n";
                system("PAUSE");
                exit(0);
                break;
            case 'r':
                system("CLS");
                doMain();
                break;
        }
    }
}

This obviously needs more work, but at least should theoretically function. In your original code you're demanding that the input value be simultaneously two different things which is an impossibility, that code will never work.

I'd also encourage you to stop doing things like system("CLS") and system("PAUSE") and instead do something in C++ natively. That's not portable code and it's terribly clunky as it depends on commands from 1980s DOS.

Comments