如何替换命令提示符中已打印的文本?

发布于 2024-12-01 16:35:55 字数 304 浏览 1 评论 0原文

我很多次看到基于文本的程序替换了已经打印的文本。例如,想象一个程序,其中打印进度为

Loading: 5%

,然后显示

Loading: 10%

等等,没有打印附加的新文本?

这是怎么做到的?我还没有在库中看到任何此类函数(在本例中为 C)。不过,我有一个想法:您可以编写一个字符,它将提示符返回到当前行的开头(我相信 \r )。这可以用来“覆盖”您已经打印到命令提示符的内容吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

枕梦 2024-12-08 16:35:55

在大多数控制台中,编写一个不带换行符的空回车符 \r 会将光标返回到当前行的开头,从而允许您覆盖现有文本。写入退格字符 \b 也会将光标向后移动一个字符。

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

在 Windows 上,有一个函数套件 用于操作控制台,它们可以做与 Unix 控制台基本相同的事情。

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.

逆夏时光 2024-12-08 16:35:55

我见过的一种方法是多次打印退格字符,然后用新文本替换您删除的内容。

退格字符是一个 ASCII 控制字符,用 \b 表示。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文