QQ said:
Hi here is my short program
Make that
int main( void )
since main() must return an integer.
{
while(1)
{
int command;
scanf("%d", &command);
switch(command)
{
case 99:
{
printf("Exit............\n");
exit(1);
}
case 0:
printf(" case 1\n");
break;
case 1:/
printf(" case 1\n");
break;
default:
printf("Please choose between 0 and 10\n");
}
}
Now when I run this program
if I input a b c or anything other than 0,1,
Actually, any integer should do, not just 0 and 1...
it will go to inifinite loop
what's the problem?
The direct problem is that you don't check the return value of scanf().
You tell it to read an integer but when there isn't one it returns 0 to
tell you that nothing has been read (scanf() always returns the number
of items it read). Since scanf() couldn't read anything everything is
still in the input buffer and when you call scanf() again it fails again
since there's still nothing in the input buffer that would match the
required integer. And with your infinite loop you only get out of that
by killing the program.
What you may learn from this is that scanf() is extremely difficult
(if possible at all) to use with user input. The strategy usually
recommended is to use e.g. fgets() to read in a whole line of input
and inspect this for what you want. Then you can discard input that
you can't deal with and, since it then doesn't stick in the input
buffer anymore, you can continue with reading the next line instead
of failing at the same piece of input over and over again.
In your simple case it might be good enough to just check the return
value of scanf() and, if it's 0, complain to the user _and_ read in
the whole offending line with fgets() to get rid of it in order to
keep scanf() chocking on it.
Regards, Jens