How to delete printed characters from command line in C++

后端 未结 2 573
礼貌的吻别
礼貌的吻别 2020-12-06 06:37

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 downloade

相关标签:
2条回答
  • 2020-12-06 07:16

    I'm not sure why you ran into problems, but either \b or \r can be used to do this, I have used \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);
        }
    }
    
    0 讨论(0)
  • 2020-12-06 07:23

    According to Wikipedia:

    The Win32 console does not support ANSI escape sequences at all. Software can manipulate the console with the ioctl-like Console API interlaced with the text output. Some software internally interprets ANSI escape sequences in text being printing and translates them to these calls [citation needed].

    Check out this: http://msdn.microsoft.com/en-us/library/ms682073.aspx

    I believe SetConsoleCursorPosition is what allows you to replace text.

    0 讨论(0)
提交回复
热议问题