0

この回答のサンプルコードを試していました。

#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%

これは同じ行で 3 回更新され、次のようになります。

[==============================] 100%

3秒後。

各進行状況バーは期待どおりに消去されますが、次の進行状況バーは、予想していたのと同じ行ではなく、1 行下に描画されます。

回答にリンクされているドキュメント(ウィキペディア)には、CSI n EESC[nE)がn整数であると書かれています:

カーソルを n (デフォルトは 1) 行下の行の先頭に移動します。

CSI 0 Eしたがって、 ( ESC[0E) はカーソルを現在の行の先頭 (行を下に移動) に移動することを期待します0

なぜそうしないのですか?また、どうすれば意図した動作を実現できますか?


Terminal.appこのプログラムを実行するために OS X を使用しています。

4

1 に答える 1

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.

これはキャリッジ リターンであり、カーソルを行頭に再配置する必要があります。

(ちなみに、あなたのコードにコメントしてくれてありがとう。ここで人々がそれをするのが大好きです:))

于 2014-08-18T03:51:45.980 に答える