0

i have this kinda game, which inputs an integer.. but my problem is, when the user inputs a char variable, the program stops. it should say that the user entered an invalid box number. but it stops scanning when the user enters a char variable. help me pls...

here is the statement where the program stops.

for(i=0;i!=1;){

			gotoxy(15,25);
			printf("Enter Box Number:   ");
			gotoxy(33,25);

			scanf("%d",&n);

				if(n>= 1 && n<= 81)
					i=1;
				else{
					i=0;
					gotoxy(15,26);
					printf("Invalid box number. Try again");
					}


			}
3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by Aia
0

>it should say that the user entered an invalid box number. but it stops scanning when the user enters a char variable.

Actually, if the variable n is initialized to or contain random data ( not initialized ) to something equal or bigger of 1 and equal or less than 81, it stops, when scanf() fails. If the variable n contains less than 1 or bigger than 81 it will enter in a forever loop, displaying the first printf() and the else printf()

Why?
scanf() reads the character, it cannot convert it, reads the next one, stops when it sees the Return or Enter key, but it doesn't remove it from the stdin buffer, reading it in the next pass over and over in a loop if nothing stops the loop.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.