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?
getcharin the outer loop eats up theq. Addputchar(ch)just before the inner loop to fix the issue. On the other hand,scanf("%d"), on invalid input such as a character, will fail, and return 0, leaving the character (invalid input) in thestdinitself. - Spikatrix