0
How would I use the switch statement to check if an answer was yes or no?
I know the switch statement can be used with numbers, but how exactly would you use it to check answers like yes or no?
3 Respuestas
+ 1
use strings instead of numbers
+ 1
Either you use characters like 'y' or 'n' as short notations for such answers, or you will have to fall back to an if - else if - else statement. Switch can only be used with data types that can be represented as numbers, however, strings can not be implicitely casted to a numeral representation and therefore can not be used as arguments for a switch statement.
+ 1
Switch can also use char.
string ans;
cout << "Yes or No? ";
cin >> ans;
switch (toupper(ans[0])) {
case 'Y':
cout << "Affirmative."; break;
case 'N':
cout << "Negative."; break;
default: cout << "Y or N please.";
};