Ask how to use the scanf function. What happened to this program?

this program blocks, then waits for you to enter an integer, then outputs it as is, and then blocks again, and so on.
(compiler: VS2005)

-sharpinclude<stdio.h>
int main()
{
    int i;
    while(1)
    {
        puts("");
        scanf("%d", &i);
        printf(":%d\n", i);
    }
}

but in fact, if the typed letters are recycled back, they will not block, but will go on in a crazy loop.

Baidu found that the scanf function will take a piece of data from the input cache (I don"t know what this is). If I enter a number, this operation will empty the input cache. When running the scanf function again, if the input cache is empty, it will cause a block.

however, I still don"t understand what happens when you enter letters.

C
Sep.06,2021

well, I finally found the answer for myself.

Another feature of

scanf is that when a character in the input cache does not match the formatting specifier, the return will be dropped immediately, and the cache character will not be deleted.
then matches the above feature: only when the input cache is empty, it will block, otherwise it will not block.
therefore, the endless loop is complete.

Menu