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");
					}


			}

Get input as a string, not an int, so that the loop can easily test for on-numeric characters and act accordingly.

>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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.