Archived

This topic is now archived and is closed to further replies.

Fractal

what's wrong with this code?

Recommended Posts

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!

Share this post


Link to post
Share on other sites
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).

Share this post


Link to post
Share on other sites