How would I use the switch statement to check if an answer was yes or no? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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?

23rd Sep 2019, 7:06 PM
Jim Moriaty
Jim Moriaty - avatar
3 Answers
+ 1
use strings instead of numbers
23rd Sep 2019, 7:33 PM
Airree
Airree - avatar
+ 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.
23rd Sep 2019, 7:34 PM
Shadow
Shadow - avatar
+ 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."; };
24th Sep 2019, 1:15 PM
Brian
Brian - avatar