如何删除从命令行打印的字符在C ++中(How to delete printed characte

2019-06-25 22:14发布

我下载一个编译器(我认为这是MinGW的,但我不知道)的一天,Windows 2000的(我一般是Mac用户,但它不是我的机器),并下载器是一个MS-DOS命令行应用程序,会显示下载进度条。 事情是这样的......

|---                 | 15%
...
|------              | 30%
...
...
|--------------      | 70%

不同之处在于它会不断地在同一行更新。 我想通过删除先前打印的字符和重新打印不同的人完成了这一程序,但我似乎无法弄清楚如何做到这一点。

我试图打印“删除”字符几种不同的方法,如(char)8\b (甚至\r ,这是我听到回溯到在一些语言行的开始),但没有这些事情的来龙去脉。

有谁知道怎么做这种东西?

编辑:这个问题已经成为特定于平台。 我想知道具体是如何做到这一点在Mac上。

Answer 1:

我不知道为什么你遇到了问题,但无论是\b or \r可用来做到这一点,我已经使用\b

#include <iostream>
#include <iomanip>
#include <string>
#include <windows.h>

// This is the only non-portable part of this code.
// Simply pause for a specified number of milliseconds
// For Windows, we just call Sleep. For Linux, you'd
// probably call nanosleep instead (with a suitable
// multiplier, of course). Most other systems (presumably)
// have (at least vaguely) similar capabilities.
void pause(int ms) { 
    Sleep(ms);
}

static const int width = 40;    

void show_percent(int i) {
     int dashes = (width * i)/100;

     std::cout << '|' << std::left << std::setw(width) << std::string(dashes, '-') << '|' << std::setw(3) << i << "%";
}

int main() {

    for (int i=0; i<101; i++) {
        show_percent(i);
        std::cout << std::string(width+6, '\b');
        pause(100);
    }
}


Answer 2:

据维基百科 :

在Win32控制台完全不支持ANSI转义序列。 软件可以操纵与文本输出的隔行扫描IOCTL般控制台API控制台。 有些软件在内部解释的文本中印刷ANSI转义序列,并将它们转换为这些调用[来源]。

看看这个: http://msdn.microsoft.com/en-us/library/ms682073.aspx

我相信SetConsoleCursorPosition是什么让你替换文本。



文章来源: How to delete printed characters from command line in C++