help me for switch statement

Write your question here:
I write a small switch statement. once I enter 1, it will show "wrong number".

thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

using namespace std;

int main()
{
    int i;
    cout<<"enter a number"<<endl;
    cin>>i;

    switch (i)
    {
        case '1':
        {cout<<"case1";
        break;}
        case '2':
        {cout<<"case2";
        break;}
        default:
        {cout<<"wrong number";
        break;}
    }


}
 

Last edited on
closed account (3qX21hU5)
Your comparing a integer value int i against a char value case '1':.

So it is skipping all your cases (because 1 is not the same as '1') and going straight to the default.
'1' is the character representation of 1. Get rid of the single quotes and the program will work as intended, or change int i; to char i;

Also the final break; is not necessary as there is no further code in the switch statement.
#include <iostream>

using namespace std;

int main()
{
char i;
cout<<"enter a number"<<endl;
cin>>i;

switch (i)
{
case '1':
{cout<<"case1";
break;}
case '2':
{cout<<"case2";
break;}
default:
{cout<<"wrong number";
break;}
}


}

it still output "wrong number"
closed account (3qX21hU5)
Please explain what you mean by "wrong number". What did you enter for the input? If you entered anything other then a 1 or 2 you will get wrong number. Do you have anything else in the program?

From what you posted it should compile and work just fine.

heebleworp wrote:
or change int i; to char i;


I would recommend against this. If you are working with numbers you shouldn't be storing them in a char variable.

Instead like was pointed out in your switch statement change the case labels to test against integers instead of chars. (Hint: Get rid of the ' ')
once i enter 1, it still show" wrong number"

include <iostream>

using namespace std;

int main()
{
int i;
cout<<"enter a number"<<endl;
cin>>i;

switch (i)
{
case 1:
{cout<<"case1";
break;}
case 2:
{cout<<"case2";
break;}
default:
{cout<<"wrong number";
break;}
}


}
closed account (3qX21hU5)
What compiler and IDE are you using? Because your code works just fine. http://ideone.com/78OjCR
i use codeblcok
Thanks, Zereo
works okay for me (vs2010)

OP: post exactly what you are compiling.
thanks, mutexe
Topic archived. No new replies allowed.