Home > other >  Why the command \r in printf() doesn't work?
Why the command \r in printf() doesn't work?

Time:12-09

I'm trying to update a text on the terminal without have to print again the text. Right now I'm trying to do it on a simple code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char *argv[]){
    for(int i=0;i<=100;  i){
        printf("\r[=%%]",i);
        sleep(1);
    }
    printf("\n");
    return 0;
}

The code literally print nothing, with the pointer blinking at the start of the line.
Can someone help me?

CodePudding user response:

The standard output stream is typically line buffered, so if you don't print a newline (i.e. \n) then the output will remain in the buffer.

After calling printf, call fflush(stdout);. This will flush the standard output stream so that you can see the text.

  • Related