1

所以我试图在代码中写一些东西,然后覆盖它。像这样:

10 seconds have passed
11 seconds have passed
12 seconds have passed

无需使用新行来打印它。所以我不想使用这样的东西:

std::cout<<"10 seconds have passed\n"
std::cout<<"11 seconds have passed\n"

我该怎么做呢?我正在运行 Kubuntu Linux

4

5 回答 5

9

That's what the carriage return character is for: \r. It is named after the mechanism of typewriters that returns the paper carriage to the right so that the typist can continue typing from the beginning of a line. Try this:

std::cout << "10 seconds have passed";
std::cout << "\r11";

Of course, with no delay between the two (except perhaps waiting on I/O), you're unlikely to see the change, but you will at least see the output as 11 seconds have passed with 10 nowhere to be seen.

How to display the carriage return is entirely up to whatever you're outputting to, but this is its intention. For more complex cross-platform terminal output, take a look at ncurses.

于 2012-11-26T20:25:36.310 回答
4
#include <conio.h>
#include <consoleapi.h>

void gotoxy(short x, short y)       
{ 
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD position = { x, y };

    SetConsoleCursorPosition(hStdout, position);
}

如果您需要更好地在控制台中移动。(我不知道为什么它没有正确显示#include conio.h

于 2012-11-26T20:39:31.547 回答
1

Try

cout<<"\roverride"

With no linebreak at the end. The \r means carage return which means to jump to the beginning of a line.

于 2012-11-26T20:25:19.040 回答
1

Besides \r (that takes you back to the beginning of the line), you can also use the \b character to get back of one character. If you have to do more complicated stuff, you'll have to use the VT100 escape codes or some library (like ncurses).

于 2012-11-26T20:26:05.713 回答
1

回车'\r'负责移回行首。

并不是说您必须覆盖所有已写入的字符,因为它们不会在显示时自动删除。

并且不要忘记调用 std::cout 的刷新,因为否则在 unix 机器上,在刷新之前您可能看不到任何结果。

于 2012-11-26T20:27:08.723 回答