C++ changing output on console

2019-03-11 05:11发布

What is the easiest way to display changing numbers in the console? I have a normal commandline program in C++ which uses cout, but I'd like to display a percentage number representing the progress which counts up to 100 without printing a new line. How is that done? (If it matters: I'm on Windows 7) Thanks for your answers!

标签: c++ console
3条回答
smile是对你的礼貌
2楼-- · 2019-03-11 05:31

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

查看更多
对你真心纯属浪费
3楼-- · 2019-03-11 05:31

Use the backspace character.

cout << "10%";
// ...
cout << "\b\b\b20%";
查看更多
你好瞎i
4楼-- · 2019-03-11 05:51

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".

查看更多
登录 后发表回答