【发布时间】:2014-10-10 22:33:41
【问题描述】:
我正在尝试来自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;
}
预期的行为是这样的进度条:
[======= ] 25%
会在同一行更新三次,结果为:
[==============================] 100%
3 秒后。
虽然每个进度条都按预期擦除,但下一个进度条会向下绘制一行,而不是我预期的同一行。
答案 (Wikipedia) 中链接的文档说 CSI n E (ESC[nE) 其中n 是一个整数:
将光标移到行首 n(默认为 1)行。
所以我希望CSI 0 E (ESC[0E) 将光标移动到当前行的开头(0 行向下)。
为什么不呢?另外,我怎样才能实现预期的行为?
我在 OS X 上使用Terminal.app 来运行这个程序。
【问题讨论】:
标签: terminal ansi-escape