I'm confused about the behavior of scanf when handling whitespace.
Here's the code I'm using:
int main()
{
int val;
int c;
scanf("%d\t", &val);
c = getchar();
if(c == EOF)
printf("eof");
else if(c == '\t')
printf("tab");
else if(c == '\n')
printf("newline");
}
And here's the input that I'm passing it:
1234<tab><newline>
I would expect this to print "newline", since the scanf is only looking for tabs, and supposedly scanf leaves whitespace in the buffer by default. Instead, it prints "eof". The %d\t
seems to be swallowing the newline.
Am I missing something about how scanf works?
Note that if I change it to the following, it correctly prints "newline":
int main()
{
int val;
int c;
scanf("%d", &val);
getchar(); /* note this extra getchar */
c = getchar();
if(c == EOF)
printf("eof");
else if(c == '\t')
printf("tab");
else if(c == '\n')
printf("newline");
}