You get this behavior because of the tail \n in the input format. He searches for empty space and does not know when he has finished scanning a space until he meets a non-white space. Do not put a trailing space in scanf() -family format lines unless you really know what you are doing or are really dealing with user input (input comes from a program or file or line).
Note that your code should check the return value from scanf() ; it will go completely into an infinite loop if it encounters an EOF (or, indeed, if it encounters a non-numeric, non-white space). In addition, when specifying such a new line, one number per input line is not applied. The user can have fun typing 1 2 3 4 5 6 7 8 9 0 on one line, and your code will cycle through the cycle evenly 9 times before getting stuck.
You can also avoid problems using fgets() (or POSIX getline() ) to read the input line, and then use sscanf() to convert the read data to a number. Note that the resulting newline is harmless.
source share