how to restrict printf output to a single line?

Special K

Diamond Member
Jun 18, 2000
7,098
0
76
I have seen programs where they print something to the console, but each new line overwrites the previous one. The most common application of this is to see something like a percentage that increases to 100, but each new increment overwrites the previous one, instead of being displayed separately. By default, if you call printf it will advance the cursor to the next space. Is there a way to keep it in place and overwrite text that has already been printed?

I hope my question make sense - it's kind of hard to describe in words what I am talking about.
 

stevf

Senior member
Jan 26, 2005
290
0
0
Try starting the print string with \r

as in:

printf("\rOutput %s", variable);

\r should also work with cout and print statements in c++ and java
 

Cerebus451

Golden Member
Nov 30, 2000
1,425
0
76
Originally posted by: stevf
Try starting the print string with \r

as in:

printf("\rOutput %s", variable);

\r should also work with cout and print statements in c++ and java
This is correct. '\r' is the carriage return character, which will return the cursor back to the beginning of the line. Also, printf by itself will not add a newline. It will print out exactly what you tell it. In stevf's example, take note of the lack of a '\n' at the end of the string getting printed out. Also note, however, that most systems won't flush what is printed to the console until a newline is encountered. To get these messages to show up you may have to add a fflush (stdout); call after the printf to ensure the message gets printed out.