I am trying to update the command line output 3 times using \r in C, but why does it skip over my second printf statement?

35 Views Asked by At

Here is my code:

#include <stdio.h>
#include <unistd.h>

int main() {
    printf("hello");
    sleep(1);
    fflush(stdout);
    printf("\rworld");
    sleep(1);
    fflush(stdout);
    printf("\r!    \n");
    sleep(1);
    return 0;
}

It displays "Hello" for a second, does nothing for another second, and then goes straight to "!" I have tried to change the sleep durations and a few other things but nothing has fixed it. What am I doing wrong?

1

There are 1 best solutions below

0
chux - Reinstate Monica On

Flush before sleep to insure timely display.

stdout buffering mechanisms are implementation defined. Yet fflush() will get the output done promptly.

int main(void) {
    printf("hello");
    fflush(stdout);
    sleep(1);

    printf("\rworld");
    fflush(stdout);
    sleep(1);

    printf("\r!    \n");
    fflush(stdout);
    sleep(1);

    return 0;
}