如何替换命令提示符中已打印的文本? [英] How to replace already-printed text in the command prompt?

查看:71
本文介绍了如何替换命令提示符中已打印的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很多时候,我见过基于文本的程序来代替已经打印的文本。例如,假设有一个程序将进度打印为

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%

,然后显示

Loading: 10%

依此类推,打印新文本,即

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

这是如何完成的?我没有在库中看到任何此类功能(在本例中为C)。不过,我有个主意:您可以写一个字符,该字符将提示返回到当前行的开头(我相信 \r )。

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?

推荐答案

在大多数控制台中,是否可以使用它们来覆盖已经打印到命令提示符的内容?完全回车符 \r 不带换行符,它将使光标返回到当前行的开头,从而使您可以覆盖现有文本。编写退格字符 \b 也会将光标移回一个字符。

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.

对于简单行为,例如a进度指示器,这就是您所需要的。对于更复杂的行为,您需要通过非标准方式控制终端。在基于Unix的系统上,可以使用 ncurses 库-它使您可以完全控制光标位置,文本颜色,键盘回声,更细粒度的键盘输入等等。

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.

在Windows上,有一个用于控制台的功能套件,它们可以完成与Unix控制台相同的功能

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

这篇关于如何替换命令提示符中已打印的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆