【问题标题】:ANSI escape code ESC[0E doesn't work as expectedANSI 转义码 ESC[0E 不能按预期工作
【发布时间】: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


    【解决方案1】:

    嗯,试试吧:

    std::cout << "\r";
    

    代替:

    std::cout << "\x1B[2K"; // Erase the entire current line.
    std::cout << "\x1B[0E"; // Move to the beginning of the current line.
    

    这是一个回车,它应该将光标重新定位在行首。

    (顺便说一句,感谢您评论您的代码。当人们在这里这样做时喜欢它:))

    【讨论】:

    • 成功了!谢谢你。但是我仍然想知道为什么"\x1B[0E" 不起作用。
    • @anthropomorphic 我最好的猜测是1——默认向下移动的行数——是可能的最小行数。毕竟,有一个 ANSI 转义码可以做你正在做的事情,但是以更简单的方式 - \x[F
    • [ 不是有效的十六进制字符。你的意思是\x1B[F
    • 我试过\1B[F,结果是光标重新定位到终端最上面一行的开头。
    • 嗯。 stackoverflow.com/questions/11474391/… 说它应该放在行首。也许试试\033[0E?只是玩转义序列,我真的不知道它是否会起作用。
    猜你喜欢
    • 2015-07-08
    • 1970-01-01
    • 2015-06-26
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多