Reputation: 2638
Does anyone know why if i put a printf just before a delay it waits until the delay is finished before it prints de message?
Code1 with sleep():
int main (void)
{
printf ("hi world");
system("sleep 3");
}
Code2 with a self implemented delay:
void delay(float sec)
{
time_t start;
time_t current;
time(&start);
do{
time(¤t);
}while(difftime(current,start) < sec);
}
int main (void)
{
printf ("hi world");
delay(3);
}
And if:
printf ("hi world");
delay(3);
printf ("hi world");
delay(3);
it waits until the sum of sleeps and then it prints the messages at the same time
Why does this happen?
UPDATE: I writed delay("sleep 3") when i called delay, i meant delay(3). Corrected
Upvotes: 6
Views: 5791
Reputation: 4435
Technically that shouldn't even compile. In the delay("sleep 3")
call you're trying to convert a const char *
to a float
. It should be:
void delay (float sec)
{
// ...
}
delay(3);
Upvotes: -1
Reputation: 8836
printf buffers it's output until a newline is output.
Add a fflush(stdout); to flush the buffers on demand.
Upvotes: 21
Reputation: 10872
When you call printf, you don't print anything until really necessary: until either the buffer fulls up, or you add a new line. Or you explicitly flush it.
So, you can either do
printf("Something\n");
delay();
or
printf("Something");
fflush(stdout);
delay();
Upvotes: 1
Reputation: 992937
Normally, standard output is buffered until you either:
\n
characterfflush(stdout)
Do one of these things before calling delay()
and you should see your output.
Upvotes: 8
Reputation: 7608
the standard output is not flush until you output a '\n' char.
try printf ("hi world\n");
Upvotes: 10