+ 1
C++ Switch statement not working as wanted
Can someone show me what I am doing wrong here? I have tried everything I could think of. I am trying to make a restaurant menu with 5 options to choose from and one option to select by default. The option by default outputs but the other options do not. Also it has to receive the input “Sandwich” or “Caesar” not numbers or letters. I have also tried if statements This is for c++ lesson 41.2 practice project. The input is “Sandwich”, “Caesar”, “Water”, … https://code.sololearn.com/cXMd548Sye1Q/?ref=app
4 Antworten
+ 4
I can't point you to a link but it looks like switch doesn't supports a string . It can accept a character or a integer(maybe other types but i don't know)
Even if string was supported your code won't work at all .You are reading a value but didn't passed it to function and int x is uninitalized with 0 or a garbage value .
+ 2
Something like this.
https://code.sololearn.com/cpCjgnc52ti5/?ref=app
0
This doesn’t work for the specific project I am doing. I need to output the menu item when the user inputs “Sandwich”, “Caesar”, “Water”. I tried this code but didn’t output anything. This is for lesson 41.2 in the c++ course.
0
Hey,
Switch statements in fact only work with integers and chars as someone else correctly pointed out.
What you can do though is access the first character of a string using string[0] and then determine your output.
I have a code bit here that uses this and then if statements if the first characters are similar. Still more elegant then using only if statements and props for checking switch statements.
https://code.sololearn.com/cS56621wUi6t/?ref=app
ignore the upper part and look at the convertToNumericMonth() method.
It uses the system described above that you can also implement in your code.