0

i have this simple code" printinterval in int

sleep(printinterval/3);
displayPrint();  //// just some printing func
sleep(printinterval/3);
displayPrint(); 
sleep(printinterval-2*(int)(printinterval/3));
displayPrint(); 

the problem is that it doest not do the delay the right way, jumps over 1 sleep

but

sleep(printinterval/3);
printf("\n");
displayPrint();  //// just some printing func
printf("\n");    
sleep(printinterval/3);
printf("\n");    
displayPrint();
printf("\n"); 
sleep(printinterval-2*(int)(printinterval/3));
printf("\n");
displayPrint(); 

works like a charm

any ideas? thx :)

EDITED: thx for the help found this way to fix it

fflush(stdout); // Will now print everything in the stdout buffer

and again, thx

JohnnyF
  • 1,053
  • 4
  • 16
  • 31
  • 2
    How is `printInterval` defined and what is its value ? – Paul R Jun 10 '14 at 08:18
  • 2
    The `printf("\n")` calls are flushing the output. In the example where you're not using them the output is probably getting buffered and you don't see some of the `displayPrint()` output until long after. – Michael Burr Jun 10 '14 at 08:19
  • 1
    This: `sleep(printinterval-2*(int)(printinterval));` doesn't make any sense, that looks like it would produce a negative delay for any positive value of `printinterval`. – unwind Jun 10 '14 at 08:25

1 Answers1

9

The stream is buffered, and flushed when a \n is encountered.

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

Community
  • 1
  • 1
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175