首页 > 解决方案 > 如何在控制台c ++中制作加载栏

问题描述

如何制作一个以加载栏形式显示进度的功能?看起来像这样的东西[----------->]

标签: c++c++11

解决方案


下面的代码,改编自这个问题。请注意,我添加Windows.h了使用该Sleep功能。这只是为了展示它是如何工作的。您可以简单地删除它,或将其更改为 *nix 工作替代方案。该函数异步运行,因此您可以在进度条尚未完全加载时执行其他操作。

#include <iostream>
#include <future>
#include <thread>
#include <Windows.h>

void load() {
    float progress = 0.0;

    while (progress < 1.0) {

        int barWidth = 70;
        int pos = barWidth * progress;

        Sleep(100);

        std::cout << "[";
        for (int i = 0; i < barWidth; i++) {
            if (i < pos) std::cout << "=";
            else if (i == pos) std::cout << ">";
            else std::cout << " ";
        }
        std::cout << "]" << int(progress * 100.0) << " %\r";
        std::cout.flush();

        progress += 0.01;
    }
    std::cout << std::endl;
}

int main() {
    std::future<void> startLoading = std::async(std::launch::async, load);
    // Do something while loading...
    for (int i = 0; i < 100; i++) {
        std::cout << i << " ";
    }
    return 0;
}

推荐阅读