Sign in to follow this  
Boooke

Switches

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,

[CODE]
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: ";
}
[/CODE]

(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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this