0

I have a slow running loop that can take an hour or more so I want to print a progress indicator. I'm using the following kind of code.

for (int i=0; i<=j; i++)
{
    pass[0] = 'A' + i;
    printf("%c", pass[0]);
\\Some slow running code omitted for brevity
}

If I use this code it will spit out ABCD...Z (or stop when it finds the answer) when then entire loop completes which defeats the purpose of having a progress indicator. But if I include a new line character \n in the printf statement, it will print ABCD out progressively while the loop is running. That is the behavior I want but unfortunately it adds a line break between each letter.

I tried to add a space and that didn't work because it won't print until the entire loop is done. I even tried using the putchar() function and that behaved the same as the printf() function where I cannot get it to progressively print out the letters unless I insert a new line between each character. Can anyone explain this behavior or what I'm doing wrong?

George Ou
  • 103
  • 1
  • 7
  • 3
    `stdout` is buffered, it takes some time until the characters are printed on screen. When `printf` sees a newline, it flushes the buffer, that's why you see that. If you don't want the newline, just add `fflush(stdout)` after the `printf`. – Pablo Feb 18 '18 at 00:33

1 Answers1

2

stdout is a buffered stream, that means that characters are going to be stored in the buffer first before they are actually printed on screen.

The printf-family of functions however flush the buffer when it encounters a newline, that's why you mostly see printf lines that end with a newline.1

Using fflush you can flush the buffer yourself. So, I you don't want the newline and also want to see the text right away, use fflush(stdout):

for (int i=0; i<=j; i++)
{
    pass[0] = 'A' + i;
    printf("%c", pass[0]);
    fflush(stdout);
}

will solve your problem.


Footnotes

1I believe this only applies for stdout, I think I read somewhere a long time ago, I can't find the source anymore. But I've found this: https://stackoverflow.com/a/4201325/1480131

Pablo
  • 12,254
  • 3
  • 31
  • 52