1

I want to test if different loops are active, so I have a print statement that repeats every 500ms in each loop, however the print statement does not print every 500ms, it waits until the loop is finished and then prints everything at once instead of periodically.

How do I get my program to print to the terminal periodically?

I'm a student so my knowledge of SDL is pretty limited so thorough explanation would be appreciated.

int main(void)
{
    int i = 0;
    while(i<10)
        {
            printf("While loop active.\t"); i++;
            SDL_Delay(500);
        }
    return 0;
}

P.S. I saw that duplicate question but I disagree as his question suggests an issue with 'signal handling' which I know nothing about so when asking this question, I didn't think his question would have the same answer as mine. I accept the answers given are the same though.

  • 5
    `printf` output in C is generally buffered. The information is accumulated internally until such time as the output driver decides it's time to really send it out. The output buffer isn't flushed until (a) it fills up (a lot of info), (b) you print a carriage/return/line-feed, or (c) you do an explicit `fflush(stdout)`. Why not use `\n` instead of `\t` then you'll see the output immediately? The tab (`\t`) output is going to be a bit messy looking. If you really must have the `\t`, then use `fflush(stdout)` after your `printf`. – lurker Jul 17 '18 at 20:13
  • @lurker Thank you very much for your well explained answer. I never understood what fflush was used for or that \n flushes while \t doesn't so this is extremely helpful. Thanks again. – Richard Robertson Jul 18 '18 at 13:30

1 Answers1

3

You are probably not flushing stdout. Add a newline to the printf call and you should be OK:

printf("While loop active.\n");
/* Here ------------------^ */

Or if keeping \t is essential:

printf("While loop active.\t");
fflush(stdout);

Credit to @lurker for extra information.

Mureinik
  • 297,002
  • 52
  • 306
  • 350