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?
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 == .
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.
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).
Personally I'd go with:
do
{
cout << "Were you admitted? [y/n]" << endl;
cin >> type;
}
while( !cin.fail() && type!='y' && type!='n' );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With