如何在终端中更新打印的消息而无需重新打印 [英] How to update a printed message in terminal without reprinting
问题描述
我想为我的终端应用程序制作一个进度条,该进度条的工作原理如下:
I want to make a progress bar for my terminal application that would work something like:
[XXXXXXX ]
可以直观地指示在该过程完成之前还剩下多少时间.
which would give a visual indication of how much time there is left before the process completes.
我知道我可以通过将它们添加到字符串中,然后简单地将printf添加到X中来进行打印,但这看起来像:
I know I can do something like printing more and more X's by adding them to the string and then simply printf, but that would look like:
[XXXXXXX ]
[XXXXXXXX ]
[XXXXXXXXX ]
[XXXXXXXXXX ]
或类似的东西(显然您可以使用空格).但这在视觉上并不美观.有没有一种方法可以用新文本更新终端中的打印文本而无需重新打印?这一切都在linux,c ++下.
or something like that (obviously you can play with the spacing.) But this is not visually aesthetic. Is there a way to update the printed text in a terminal with new text without reprinting? This is all under linux, c++.
推荐答案
在打印新的版本"时尝试使用\r
而不是\n
.
try using \r
instead of \n
when printing the new "version".
for(int i=0;i<=100;++i) printf("\r[%3d%%]",i);
printf("\n");
这篇关于如何在终端中更新打印的消息而无需重新打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!