I have constructed this program which creates a random number and asks the user to guess what it is. The users' first guess is replied with either "the number is too high or low. guess again". I am trying to do error checking. If the user inputs a negative number or a number about 1023 then this error check works ok. But when I input a letter or special character, the program enters into an infinite loop. Can you tell me why this is happening and what I need to do to correctly check this, please?
thank you
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
//seed PRNG
srand(time(NULL));
//pick pseudorandom number in [0, 1023]
int randomNum = rand() % 1024;
int num;
//prompts to user and guesses from user
printf("I'm thinking of a number between 0 and 1023. What is it?\n");
scanf("%d", &num);
while(num != randomNum){
if(num < 0 || num > 1023){
printf("Sorry. That is not a number between 0 - 1023. Please try again\n");
scanf("%d", &num);
}
else if(num > randomNum){
printf("Sorry. The number is lower than that. Please try again\n");
scanf("%d", &num);
}
else if(num < randomNum){
printf("Sorry. The number is higher than that. Please try again\n");
scanf("%d", &num);
}
else{
printf("That is not a number. Please input a number between 0 - 1023\n");
scanf("%d", &num);
}
}
printf("Well done! That was the number I was thinking of\n");
return 0;
}

New Topic/Question
Reply



MultiQuote



|