scanf
is weird. It has an internal buffer, and will only read from the stream if that buffer is empty. At the start of your code, there is nothing, so a line is read from standard input. Then scanf
tries to find an integer there. If an integer is found, it will report it successfully read one item (by returning 1
) and puts the read value into the supplied pointer location. However, if an integer is not found, it will return 0
for "zero items successfully read", and it will not consume anything from the buffer. This means, next time scanf
is invoked, the buffer will not be empty, consequently the user will not be prompted again for a new line, and scanf
will try again to read an integer at exactly the same place it tried last time (and will fail for exactly the same reason). Thus, infinite loop.
To illustrate this "buffer" thing, try this:
scanf("%d", &a);
scanf("%d", &b);
printf("a: %d, b: %d\n", a, b);
and enter 12 53
in one line, as the input to the first scanf
. Magically, a
ends up as 12
and b
ends up as 53
. The explanation for the magic is - the first scanf
found the buffer empty, read the line from the user, and found one integer, as it was told to; the second scanf
found the buffer with some stuff still there, and continued reading where it left off last without having to ask the user for a new line.
As others commented already, it is usually better to read a line yourself (fgets
) and parse it yourself (strtol
), or if you absolutely need to use scanf
, make sure to check if scanf
read what you expected it to by inspecting its return code. See here on how to clear the input buffer if scanf
fails.