Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safely prompt for yes/no with cin

Tags:

c++

user-input

I'm in an intro to C++ class and I was wondering of a better method of checking if input was the desired type.

Is this a good way of doing this? I come from a PHP/PERL background which makes me rather apprehensive of using while loops.

char type;
while (true) {
    cout << "Were you admitted? [y/n]" << endl;
    cin >> type;

    if ((type == 'y') || (type == 'n')) {
        break;
    }
}

Is this a safe way of doing this or am I opening myself up to a world of hurt, which I suspect? What would be a better way of making sure I get the input I want before continuing?

like image 391
Levi Avatar asked Feb 05 '10 17:02

Levi


People also ask

How do you ask for yes or no in C++?

Note that compare will return 0 when the strings are equal. So input. compare("Yes") will evaluate to false when the input is "Yes" and to true for any other input. Simply use == .

How does C++ handle invalid input?

The thing to do is to clear that flag and discard the bad input from the input buffer. See the C++ FAQ for this, and other examples, including adding a minimum and/or maximum into the condition.

What is the limitation of std :: cin?

Unfortunately, std::cin does not support this style of validation. Since strings do not have any restrictions on what characters can be entered, extraction is guaranteed to succeed (though remember that std::cin stops extracting at the first non-leading whitespace character).


1 Answers

Personally I'd go with:

do
{
    cout << "Were you admitted? [y/n]" << endl;
    cin >> type;
}
while( !cin.fail() && type!='y' && type!='n' );
like image 127
McAden Avatar answered Sep 24 '22 10:09

McAden