I'm confused about how scanf and getchar handle stream differently, the following is a sample code:
while(scanf("%d", &input) != 1)
{
while((ch = getchar()) != '\n')
{
putchar(ch);
}
printf("\nThis is wrong\n");
}
printf("That is right\n");
It is a simple program used to test if the input is a integer. The inner while loop is used to display every wrong input value before click Enter. When I entered a random string such as:
qwert
putchar will print out the exact string. However, if I replaced
while(scanf("%d", &input) != 1)
with
while((ch = getchar()) != '\n')
and print out the exact same string, the first letter "q" is dropped out. So my question is how do scanf and getchar in the outer loop handle this situation differently?
When you use scanf
to try and read an integer, and you give some input that is not an integer, then scanf
will fail and not return 1
. It will however leave the input intact, it won't extract anything from the input, leaving it all for your inner loop to digest and print.
If you use getchar
in the outer loop, it will actually consume a single character, no matter what character it is, and the inner loop will then not see that character since it doesn't exist in the input buffer anymore.