#include <iostream>
usingnamespace std;
int main ()
{
int num_1;
cout << "Please enter your Position in Class\n";
cin >> num_1;
switch (num_1)
{
case'1':
cout << "Excellent\n";
break;
case'2':
cout << "Good\n";
break;
default:
cout << "That is not a possible grade\n";
}
cout << " \n";
cout << "End of Program\n";
return 0;
}
Second program runs fine but when I enter input, it is just showing default case only why?
#include <iostream>
usingnamespace std;
int main ()
{
int num_1;
cout << "Please enter your Position in Class\n";
cin >> num_1;
switch (num_1)
{
case 1: // not 1 and not '1'
cout << "Excellent\n";
break;
case 2: // note 2 and not a '2'
cout << "Good\n";
break;
default:
cout << "That is not a possible grade\n";
}
cout << " \n";
cout << "End of Program\n";
return 0;
}
Because num_1 is an integer and '1' and '2' are chars. They are not of the same type, so they will never be true.
The reason is a little different. '1' and '2' are the encodings for those characters (numbers 49 and 50 respectively if the computer uses ASCII encoding). So case'1' is like saying case 49 (except that one is an char and the other is an int.
The compiler can compare integers to chars just as it can compare integer to long. It promotes the narrower type to the wider type using well defined rules.