C++ Change Output From “cout”

2019-01-28 02:57发布

问题:

Is it possible to change text printed with "cout"? I would like to make it show the current percentage of something without having to have a new line for each percentage. Is this possible?

回答1:

This works for me:

std::cout << "1111";
std::cout << "\r";
std::cout << "2222";

\r is a carriage return symbol. Puts the "cursor" back to the beginning of the line.

Alternatively you can use \b character. This is backspace. When printed it goes one character back.



回答2:

In general it is not possible. (imagine that the output from cout is fed directly to a printer. How would you instruct it to "unprint" the last line?) cout is an output stream, it makes no assumptions about which medium the output is sent to, or about the capabilities of that medium. Specific tricks can achieve what you want in some cases, but will fail horribly in others. If you want anything more dynamic than straight output of plain text, perhaps cout isn't the right tool to use.



回答3:

One thing that you will definitely not get from cout is terminal line length. As this can be changed, you might use too long lines, which (using '\r') will cause printing new lines every update. If you want to use specific platform then use platform-specific functions to obtain terminal size (mind that you might not be attached to any terminal at all, eg. redirected to file).