6

I want to make my program to print something, then wait for a few seconds and then print something else in the same line. I've tried to write it as:

printf ("bla bla bla");
sleep (2);
printf ("yada yada yada\n");

but in the output I get to wait for 2 seconds and then I get the whole line printed as one. When I tried to put the output in different lines it did print with a pause.

How do I make it to print with a pause in the same line?

*Working on Linux

SIMEL
  • 8,246
  • 23
  • 76
  • 115
  • Depending on you need `fflush` can be only the beginning of the problem. See [my answer](http://superuser.com/q/239893/1711) to a question since moved to SuperUser for a moderately complete, working example. – dmckee --- ex-moderator kitten Apr 15 '11 at 18:50

2 Answers2

17
printf ("bla bla bla");
fflush(stdout);
sleep (2);
printf ("yada yada yada\n");

fflush forces the stdout internal buffer to be flushed to the screen.

GWW
  • 39,395
  • 8
  • 104
  • 101
3

The stdout is a line buffered stream by default, this means you need to explicitly flush it. It is implicitly flushed on newline. This behavior is mandated by the C99 standard.

This means in your first printf, the text is added to an internal buffer. This is done to improve efficiency, e.g. when printing lots of small text fragments.

Your second printf contains a newline, and that causes the stream to get flushed. You can explicitly flush stdout via fflush(stdout); if you want.

As an alternative you could also use the unbuffered stderr, as in fprintf(stderr, "bla bla bla");, but as its name implies it is intended for errors and warnings.

See also the SO question Why does printf not flush after the call unless a newline is in the format string?.

Community
  • 1
  • 1
DarkDust
  • 85,893
  • 19
  • 180
  • 214