简体   繁体   中英

printf sleep \n

I was trying something when I saw this strange behavior. Can someone please explain it to me.

#include<stdio.h>
int main()
{
    printf("utkarsh");
    sleep(10);
    printf("dixit");
}

The expected output is print "utkarsh" then wait for 10 seconds, print "dixit" next to it. But what I observed was that it waits for 10 seconds and the prints "utkarshdixit".

If I add a \\n at end of utkarsh, it works as expected.

printf("utkarsh\n");

Could someone help me understand why am I seeing such behavior ?

you're encoutering buffering.

try to do

fflush(stdout);

in front of the sleep

printf is buffering until you decide to write a '\\n' .

You can use : flush to force to print

Here, try this

#include<stdio.h>
int main()
{
    printf("utkarsh");
    fflush(stdout);
    sleep(10);
    printf("dixit");
}

There's buffering of the standard out going on. you have to explicitly flush it.

There is buffering in stdout stream. Hence you need to flush once before sleep.

But when you used a '\\n', the c run-time automatically flushes the stdout buffer for you. Hence you see this behaviour

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM