I used a scanf() inside a while loop.
while(1)
{
int input = 0;
scanf("%d\n", &input);
printf("%d\n", input);
}
When I run this program, and I enter a number, the printf()
is not displaying that number unless I enter another number again. Why?
The \n
in your scanf
format is interpreted as "any amount of whitespace". It keeps reading whitespace (spaces, tabs, or carriage returns) until it hits something that isn't whitespace.
You get that behaviour because of the trailing \n
in the input format. That looks for white space, and doesn't know when it has finished scanning white space until it comes across a non-white space character. Don't put trailing white space in your scanf()
-family format strings unless you really know what you're doing or you aren't actually dealing with user input (the input comes from a program or file or string).
Note that your code should be checking the return value from scanf()
; it will go into an infinite loop fully if it encounters EOF (or, indeed, if it encounters a non-numeric, non-white space character). Also, specifying the newline like that does not enforce one number per input line. The user might merrily type 1 2 3 4 5 6 7 8 9 0
on a single line, and your code will equally merrily cycle 9 times around the loop before getting stuck.
You can also evade the problems by using fgets()
(or POSIX
getline()
) to read a line of input and then use sscanf()
to convert the read data into a number. Note that the trailing newline is then harmless.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With