简体   繁体   English

C ++在控制台上更改输出

[英]C++ changing output on console

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 percentage number representing the progress which counts up to 100 without printing a new line. 我在C ++中有一个使用cout的普通命令行程序,但是我想显示一个代表进度的百分比数字,该数字最多可以计数100,而无需打印新行。 How is that done? 怎么做? (If it matters: I'm on Windows 7) (如果重要:我使用的是Windows 7)

When I've needed that I have just output a carriage return character, in C++ \\r . 需要时,我只需在C ++ \\r输出一个回车符即可。

Remember to flush the output each time, eg 记住每次都要刷新输出,例如

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

The spaces at the end to clear previous output on the line in case of Microsoft-like fluctuating progress. 末尾的空格用于清除行上以前的输出,以防类似Microsoft的进度波动。

在此处输入图片说明

Use the backspace character. 使用退格字符。

cout << "10%";
// ...
cout << "\b\b\b20%";

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. 顺便说一句,对于这种状态/诊断信息,我更喜欢使用cerr而不是cout,以便可以将cout保留用于实际内容。 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". 另外,使用cerr,您不必使用“ flush”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM