Switches

This topic is 2126 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hello, I have a minor problem. I really do not understand why my switch-statement is failing. I made a quick switch-statement as following,

 char ch; while (cin.get(ch) && ch != 'q') { switch (ch) { case '1': cout<< "Hej"; break; case '2': break; case 'q': break; default : cout << "Wrong input.\n\n"; } cout << "Choice: "; } 

(The editor has messed a bit with the indenting)

Anything except case 'q' turns to default case AND it includes the case ouput aswell.
For instance, If I enter '1', it will output "HejChoice: Wrong input." (Choice and "Wrong input" is in the wrong order aswell?). This code only works in case 'q', which do not go through the default case - Which is quite weird, because it did not work before when I chose to move the cin.get(ch) into the while-loop and only place a "1" as the condition of the loop. Then it would return "Wrong input" when I pressed 'q'.

In fact, that means case '2' do not work, since break should avoid the default case, but it still outputs "Choice: Wrong input."

I hope someone sees my code flaws, because its quite weird to me. I have used switch-statements many times, and now it seems like I forgot how to use them all in a sudden? I tried googling source-codes, too, but I could not differ my switch from other peoples' switches.

Regards,
Boooke

Share on other sites
It's likely that the switch statement is working properly, but your while loop isn't doing what you want. When you supply input to your program you're probably doing something like hitting '1' 'enter'. Your loop would then process both the '1' and then the 'enter' as two separate passes through your switch.

Share on other sites
That was it, thank you! I put a cin.ignore() call just after the cin.get(). I also thought of just ruling out this factor by using getch(), but it seems to be deprecated.

Share on other sites
You could also use std::string line; std::getline(std::cin, line). You can add code to reject any line that doesn't consist of a single character.

Share on other sites
I didn't think that switches would accept strings? Or maybe it changes if the string only consist of one element?

Share on other sites
A switch doesn't accept a string, but you can use the [] operator to get an individual character in the string. You can also dump the string into a stringstream and use the >> operator to try to parse an int from the string and switch on that. You can also fall back to if/else blocks. And so on. There are a lot of options to do what you're trying.