简体   繁体   English

C++ output 的就地计数器

[英]In place counter for C++ output

I'd like to format the output of my program to print a number (index) then some text, and the number incriments as the program progresses.我想格式化我的程序的 output 以打印一个数字(索引)然后是一些文本,并且随着程序的进行,数字会增加。 I'm using CLion, but I'd be interested to know if any solutions are 'universal'.我正在使用 CLion,但我很想知道是否有任何解决方案是“通用的”。

I've experiemted with flushing the output and system CLS:我已经尝试过冲洗 output 和系统 CLS:

cout << i << ".  has been checked" << flush;
cout << system ("CLS");

in a few different configurations but I get the feeling this is not the way.在一些不同的配置中,但我觉得这不是办法。

Formally, there's no answer, but quite a few systems support \b for backspace.形式上,没有答案,但相当多的系统支持\b退格。

It's a good programming exercise to try this - remember that you need to backspace each digit that's been printed.这是一个很好的编程练习来尝试这个 - 请记住,您需要退格打印的每个数字。 So when you go from 99 to 100, you need \b\b .所以当你 go 从 99 到 100 时,你需要\b\b And if you increment by varying steps (eg for "bytes downloaded") you need to keep track of how many digits are already on the screen.如果您通过不同的步骤递增(例如“下载的字节数”),您需要跟踪屏幕上已经有多少位。

Assuming that the vertical position of the output never changes, use a carriage return character ( \r ) for this.假设 output 的垂直 position 永远不会改变,请为此使用回车符 ( \r )。

std::cout << "\r" << i << ".  has been checked";

The \r just sets the position of the cursor to the beginning of the line. \r只是将 cursor 的 position 设置为行首。

If this doesn't do what you want, or you are outputting text after writing out i , then you need a more platform specific solution;如果这不能满足您的要求,或者您在写出i后正在输出文本,那么您需要一个更特定于平台的解决方案; move/wmove with ncurses on Linux and SetConsoleCursorPosition on Windows, for example.例如,使用 Linux 上的ncursesSetConsoleCursorPosition上的 SetConsoleCursorPosition移动/wmove

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

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