Reputation: 1112
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?
Upvotes: 4
Views: 882
Reputation: 755010
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.
Upvotes: 2
Reputation: 860
scanf("%d\n", &input);
I usually just go with the follow
scanf("%d", &input);
without the "\n"
Upvotes: 1
Reputation: 158609
If you look at a reference for scanf you will see that:
The format string consists of whitespace characters (any single whitespace character in the format string consumes all available consecutive whitespace characters from the input)
So the \n
will trigger this effect, if you don't want this behavior just leave out the \n
:
scanf("%d", &input);
Upvotes: 1
Reputation: 64308
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.
Upvotes: 5