tags:

views:

87

answers:

3

I'm having problems with this snippet of code:

   while(scanf("%d",&numOfPlayers)!=1){
        printf("Please enter the right number of players");    
    }

My purpose is to read a number from the user, and keep asking as long as the input isn't an int. When I run this snippet and input 'r' for example, I get stuck in an infinite loop. What might be the problem, and how can I improve it?

+1  A: 

Try scanning for a string into a buffer and then searching that string for your number with sscanf().

thelaws
how can I do it without sscanf?
lego69
you could check the return of atoi() instead of using sscanf()
thelaws
@thelaws: `atoi` will give no indication of failure. Use `strtol`/`strtoul` instead.
jamesdlin
@jamesdlin: Won't atoi() return 0 on failure? I know that it's a poor return value considering that it returns the converted number on success and if the user entered 0 you're out of luck, but that is why I initially suggested the use of sscanf() instead.
thelaws
+3  A: 

If scanf() can't read the input, it actually doesn't read it, so it reads the same input over and over again in your example. You can discard the invalid input like this:

while(scanf("%d",&numOfPlayers)!=1){
  scanf("%s");
  printf("Please enter the right number of players\n");
}
svick
Can you please cite a source backing up your claim that `scanf("%s")` is safe?
jamesdlin
“If the number of conversion specifications in format exceeds the number of pointer arguments, the results are undefined.” So the result depends on the compiler and may be unpredictable.
svick
Exactly, so you shouldn't be advocating doing that. Also, *undefined* behavior is distinct from *unspecified* and *implementation-defined* behavior. It means that *anything* at all can happen; you must not depend on it even for a specific compiler.
jamesdlin
+1  A: 

From the comp.lang.c FAQ: Why does everyone say not to use scanf? What should I use instead?

jamesdlin