7

Possible Duplicate:
Why does printf not flush after the call unless a newline is in the format string?

When I run something like

for (i = 1; i <= 10; i++) {
    sleep(1);
    printf(".");
}

then what I would expect is one dot per second ten times. What I get is ten dots once after ten seconds. Why is that so, and how do I get the program to actually print one point (or do other things) each second (or different time interval)?

Community
  • 1
  • 1
foaly
  • 322
  • 2
  • 3
  • 10
  • 1
    _how to sleep in c_ ? Try `for (int i = 0; i < big_number; i++) ;` and disable optimization. I have production code here (not mine) that actually does that ^_^ – Bitterblue Apr 15 '14 at 10:18

1 Answers1

11

The printf() is buffering the data, you can force it to flush that data with fflush(stdout):

for (i = 1; i<=10; i++) 
{  
    sleep(1); 
    printf("."); 
    fflush(stdout);
}
Mike
  • 40,613
  • 26
  • 100
  • 171