Print on the same line with a pause in C

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

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

but at the output I waited 2 seconds, and then I get the whole line printed as one. When I tried to put the output on different lines, it paused printing.

How to do this for printing with a pause in one line?

* Work with Linux

+6
source share
2 answers
 printf ("bla bla bla"); fflush(stdout); sleep (2); printf ("yada yada yada\n"); 

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

+17
source

By default, stdout is a line-buffered stream, which means you need to clear it explicitly. It is implicitly cleared of a new line. This behavior is provided by the C99 standard.

This means that in the first printf text is added to the internal buffer. This is done to increase efficiency, for example. when printing a large number of small fragments of text.

The second printf contains a new line, and this leads to loss of flow. You can explicitly reset stdout via fflush(stdout); , if you want to.

Alternatively, you can 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 is printf not reset after a call, unless a newline is specified in the format string? .

+3
source

Source: https://habr.com/ru/post/886010/


All Articles