2

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[%3d%%]",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?

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
ilaario
  • 23
  • 5

1 Answers1

3

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.

dbush
  • 205,898
  • 23
  • 218
  • 273