-
beginner ?
when i type anything but a number the program starts a endless loop. what code can i write into the program to stop this ,and what causes the loop.
Code:
#include <stdio.h>
int main()
{
int x;
printf("enter a numbr 1 thru 10\n");
scanf("%d",&x);
if (x<1 || x>10)
main();
else
printf("\nyou typed %d",x);
return(0);
}
-
scanf doesn't catch the carriage return very well, so in your loop when it comes back around their is a carriage return in the buffer. This carriage return seem to remain in there and thus causes your infinite loop.
This might work better for you:
Code:
#include <stdio.h>
int main() {
int x = 0;
char junk;
while ( x < 1 || x > 10 ) {
printf( "enter a numbr 1 thru 10\n" );
scanf( "%d%c", &x, &junk );
}
printf("\nyou typed %d",x);
return(0);
}
-
First you'll need to check the return value of the scanf function to see if the user really entered a number:
Code:
if(scanf("%d", %x) != 1)
printf("This is not a number.\nPlease try again.\n");
Then you'll need to get rid of the newline character, which is still in your input buffer:
Code:
while(getchar() != '\n') /*do nothing */;
Dharh, you example works on valid input but not if the user enters characters in stead of numbers. It's better to use the getchar function in a loop to remove the newline character.