How to replace already-printed text in the command

2020-07-27 03:23发布

问题:

A lot of times I've seen text-based programs which replace text which has already been printed. For instance, imagine a program where the progress is printed as

Loading: 5%

and then it says

Loading: 10%

and so on, without printing new text which is appended?

How is this done? I haven't seen any such functions available in the library (in this case C). I have an idea, though: There is a character you can write which returns the prompt to the beginning of current line (\r I believe). Could this be used to "overwrite" what you've already printed to the command prompt?

回答1:

In most consoles, writing a bare carriage return \r without a newline after it will return the cursor to the beginning of the current line, allowing you to overwrite the existing text. Writing the backspace character \b also moves the cursor back one character.

For simple behavior, such as a progress indicator, this is all you need. For more complex behavior, you need to control the terminal through non-standard means. On Unix-based systems, the ncurses library can be used—it gives you full control over the cursor location, text color, keyboard echoing, more fine-grained keyboard input, and more.

On Windows, there's a suite of functions for manipulating consoles, and they can do mostly the same things as Unix consoles.



回答2:

One way that I have seen is to just print the backspace character a number of times and then replace whatever you erased with the new text.

The backspace character is an ASCII control character represented by \b.