[英]ANSI escape code ESC[0E doesn't work as expected
I was trying out the example code from this answer . 我正在从这个答案中尝试示例代码。
#include <iostream>
#include <thread>
#include <chrono>
void drawProgressBar(int, double);
int main() {
drawProgressBar(30, .25);
std::this_thread::sleep_for(std::chrono::seconds(1));
drawProgressBar(30, .50);
std::this_thread::sleep_for(std::chrono::seconds(1));
drawProgressBar(30, .75);
std::this_thread::sleep_for(std::chrono::seconds(1));
drawProgressBar(30, 1);
return 0;
}
void drawProgressBar(int len, double percent) {
std::cout << "\x1B[2K"; // Erase the entire current line.
std::cout << "\x1B[0E"; // Move to the beginning of the current line.
std::string progress;
for (int i = 0; i < len; ++i) {
if (i < static_cast<int>(len * percent)) {
progress += "=";
} else {
progress += " ";
}
}
std::cout << "[" << progress << "] " << (static_cast<int>(100 * percent)) << "%" << std::flush;
}
The expected behavior was a progress bar like so: 预期的行为是如下所示的进度条:
[======= ] 25%
which would update three times on the same line, ending up as: 这将在同一行上更新三次,最终结果是:
[==============================] 100%
after 3 seconds. 3秒后。
While each progress bar gets erased as expected, the next progress bar is drawn one line down, not on the same line as I was expecting it to. 虽然每个进度条都按预期方式被擦除,但下一个进度条却向下绘制了一行,而不是我期望的那样。
The documentation linked in the answer ( Wikipedia ) says that CSI n E
( ESC[nE
) where n
is an integer: 答案中链接的文档( Wikipedia )说CSI n E
( ESC[nE
),其中n
是整数:
Moves cursor to beginning of the line n (default 1) lines down. 将光标向下移动到第n行(默认为1)行的开头。
So I would expect CSI 0 E
( ESC[0E
) to move the cursor to the beginning of the current line (the line 0
lines down). 因此,我希望CSI 0 E
( ESC[0E
)将光标移动到当前行的开头(第0
行向下)。
Why doesn't it? 为什么不呢? Also, how can I achieve the intended behavior? 另外,如何实现预期的行为?
I'm using Terminal.app
on OS X to run this program. 我正在OS X上使用Terminal.app
运行此程序。
Hmm, try: 嗯,尝试:
std::cout << "\r";
instead of: 代替:
std::cout << "\x1B[2K"; // Erase the entire current line.
std::cout << "\x1B[0E"; // Move to the beginning of the current line.
This is a carriage return , which should reposition the cursor at the beginning of the line. 这是回车 ,应将光标重新定位在行的开头。
(By the way, kudos for commenting your code. Love it when people do that on here :) ) (顺便说一句,为注释您的代码而声名狼藉。当人们在这里这样做时就喜欢它:))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.