C++ changing output on console

后端 未结 3 628
温柔的废话
温柔的废话 2021-02-02 16:14

What is the easiest way to display changing numbers in the console? I have a normal command line program in C++ which uses cout, but I\'d like to display a percenta

相关标签:
3条回答
  • 2021-02-02 16:39

    When I’ve needed that I have just output a carriage return character, in C++ \r.

    Remember to flush the output each time, e.g.

    cout << "\r" << x << "% completed.       " << flush;
    

    The spaces at the end to clear previous output on the line in case of Microsoft-like fluctuating progress.

    enter image description here

    0 讨论(0)
  • 2021-02-02 16:44

    Use the backspace character.

    cout << "10%";
    // ...
    cout << "\b\b\b20%";
    
    0 讨论(0)
  • 2021-02-02 16:45

    I normally place a carriage return after the progress information. That way, any other output will appear normal (as long as it has enough characters in the line to completely overwrite the progress info).

        cerr<<percentage<<"% \r";
    

    By the way, I prefer to use cerr instead of cout for this kind of status/diagnostic information so that cout can be reserved for real content. This way you can redirect the normal program output to a file and still see the progress in the console. Also, with cerr, you don't have to use "flush".

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