Home>
Contents of question

Regarding the following two codes, the first code is displayed normally when executed, but the second code is not displayed when executed.
The second code will be displayed normally after removing sleep (1).
Why is this happening?

code
#include<stdio.h>
main ()
{
    while (1)
    {
        printf ("aaaa \ n");
        sleep (1);
    }
}
#include<stdio.h>
main ()
{
    while (1)
    {
        printf ("aaaa");
        sleep (1);
    }
}
c
  • Answer # 1

    The default behavior of terminal output is that the output string is stored in a buffer in memory until a line feed code appears (or until the buffer is full), and is output to the terminal when a line feed occurs. I will.
    (If you wait for a long time, the buffer will fill up soon, so it will be output at once at that point)

    printf ("aaaa");After the,fflush (stdout);Is easy to write.

    aside from that,stderrThere are settings such as outputting to, and setting not to buffer.

  • Answer # 2

    Generally, standard output isBufferingWill be done. If buffering such as "no output until there is a line break" is performed, the latter will not start output until the buffer is full.

    setvbufTo change the buffering behavior withfflushYou can control such as writing out all the contents of the buffer with.