Safely prompt for yes/no with cin

Levi picture Levi · Feb 5, 2010 · Viewed 26.1k times · Source

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?

Answer

McAden picture McAden · Feb 5, 2010

Personally I'd go with:

do
{
    cout << "Were you admitted? [y/n]" << endl;
    cin >> type;
}
while( !cin.fail() && type!='y' && type!='n' );