I am new to C++ and I am stuck on the switch statement because it doesn’t seem to give an output when the value in the parentheses is an integer (Console-Program ended with exit code: 0). Although, the same code works fine when I change the type to char.
Thank You.
int main()
{
int num1; // argument of switch statement must be a char or int or enum
cout<< "enter either 0 or 1" << "n";
cin>> num1;
switch (num1)
{
case '0':
cout<< "you entered 0" << endl << endl;
break;
case '1':
cout<< "you entered 1" << endl << endl;
break;
}
}
2
Answers
You are switching on an
int
, which is correct, but your cases are not integers – they arechar
since they are surrounded in'
.‘0’ is never equal to 0, nor is ‘1’ ever equal to 1.
Change the case values to integers.