如何在C ++中从命令行中删除打印字符 [英] How to delete printed characters from command line in C++

查看:774
本文介绍了如何在C ++中从命令行中删除打印字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是下载一个编译器(我认为是MinGW,但我不确定)在Windows 2000的另一天(我一般是一个Mac用户,但它不是我的机器),下载是一个MS-DOS命令行应用程序,将显示下载的进度条。这样的东西...

I was downloading a compiler (I think it was MinGW but I'm not sure) on windows 2000 the other day (I'm generally a Mac user, but it wasn't my machine), and the downloader was a MS-DOS command line app that would display a progress bar for the download. Something like this...

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

,除了它将在同一行上连续更新。我假设程序通过删除以前打印的字符并重新打印不同的字符,但我似乎不知道如何做到这一点。

except that it would continuously update on the same line. I assume the program accomplished this by deleting previously printed characters and reprinting different ones, but I can't seem to figure out how to do this.

我已经尝试打印一个'删除'字符若干不同的方式,如(char)8 \b $ c> \r ,我听说回到一些语言的开头行),但这些都没有效果。

I've tried to print a 'delete' character several different ways, like (char)8 and \b (even \r, which I heard backtracks to the beginning of the line in some languages), but none of those things worked.

有人知道如何做这样的东西吗?

Does anyone know how to do this sort of stuff?

编辑:这个问题已经成为平台特定。我想知道如何在Mac上完成这个。

This question has become platform-specific. I want to know specifically how to accomplish this on a Mac.

推荐答案

我不知道为什么你遇到问题,可以使用'\ b \r`来执行此操作。

I'm not sure why you ran into problems, but either '\bor\r` can be used to do this.

#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);
    }
}

这篇关于如何在C ++中从命令行中删除打印字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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