Advertisement

what's wrong with this code?

Started by October 15, 2001 05:29 PM
0 comments, last by Fractal 23 years, 2 months ago
int Num; int Player; while(true) { printf ("\nWhat class of wizard do you want to be?\n" "1 : Fire\n" "2 : Water\n" "Press 1, 2, only - or face the consequences.\n"); scanf ("%d", &Num); if (Num == 1) {Player = 1; break;} else if (Num == 2) {Player = 2; break;} else if (Num == 3) {Player = 3; break;} else if (Num == 4) {Player = 4; break;} else if (Num == 5) {Player = 5; break;} else {printf ("\nThat''s not a valid entry, please\n" "try again\n");} } Please could you help me out here! If I type 1 or 2, it works fine. If I type a different number, it tells me to try again. But if I typr in a letter, not a number, then it crashes. Help!
Could I be any dumber?(What do you mean, "No"?)
You''ve just experienced first-hand one of the main downfalls of the scanf() function- if you input the wrong type, it crashes. Try using getch() to read a character instead. getch() will wait for the user to press a key then return its char value. Ex:

char myChar;
myChar = getch();
if (myChar == ''1''){ //etc;

This way the user won''t have to even press enter when he''s done. Notice this only works for 1 to 10 (1 to 0 on the keyboard). But you could also do a to z as well, and even A to Z (uppercase letters).

This topic is closed to new replies.

Advertisement