Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
C++ switch not working? What did I do wrong?
do{
int ALIVE=50000;
char ch=0;
ch = getche();
switch(ch){
case 1:
printf ("Case 1:");
break;
case 2:
printf ("Case 2:");
break;
case 3:
printf ("Case 3:");
break;
case 4:
printf ("Case 4:");
break;
case 6:
printf ("Case 6:");
break;
case 7:
printf ("Case 7:");
break;
case 8:
printf ("Case 8:");
break;
case 9:
printf ("Case 9:");
break;
default:
cout << "in default" << endl;
}
} while (ALIVE==50000);
In my code, this just keeps going straight to the default...
Wish I could give you both 50 points!
3 Answers
- 9 years agoFavorite Answer
getche() only receives the input as STRING. But SWITCH uses only the INTEGER as input. So U must convert the input to an Int. There is also another mistake u have done. As alive is an Int then u can assign less than 32767 (IE 50000 is much greater). Or you have to use "long" instead of "int" as datatype.
Here is the appropriate code--
int alive=5000;
do{
char ch=0;
ch = int(getche());
switch(ch)
{
case 1:
printf ("Case 1:");
break;
case 2:
printf ("Case 2:");
break;
case 3:
printf ("Case 3:");
break;
case 4:
printf ("Case 4:");
break;
case 6:
printf ("Case 6:");
break;
case 7:
printf ("Case 7:");
break;
case 8:
printf ("Case 8:");
break;
case 9:
printf ("Case 9:");
break;
default:
printf ("in default");
}
} while(alive==5000);
It is totally right & tested. If it helps then Plz vote me :)
Source(s): *ME* - llafferLv 79 years ago
If ch is the character that is captured from the user, then the value would be a valid ASCII value where 32 is space, followed by symbols, then numbers, Capital letters, then lower case letters.
Your case checks would have to either be the ASCII values you are looking for, or the character value you are expecting:
case 'a':
case 'b':
etc.
- Anonymous9 years ago
does it get the integer value of the character you input? If you want to switch on the character you should put it in single quotes. case '1' ...