【问题标题】:How to make a loading bar in the console c++如何在控制台c ++中制作加载栏
【发布时间】:2019-03-15 23:59:45
【问题描述】:

如何创建一个以加载栏形式显示进度的函数?看起来像这样的东西[----------->]

【问题讨论】:

标签: c++ c++11


【解决方案1】:

试试这样的。

void draw_bar(float numerator, float denominator, float size)
{
    float current_position = (float)(numerator / denominator) * (float)size;
    cout << "[";
    for (int i = 0; i < current_position; i++)
        i != current_position - 1 ? cout << '-' : cout << '>';
    for (int i = 0; i < size - current_position; i++)
        cout << " ";
    cout << "]";
    return;
}

【讨论】:

    【解决方案2】:

    下面的代码,改编自this question。请注意,我添加了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;
    }
    

    【讨论】:

    • 如果 Stack Overflow 上的另一个答案也回答了这个问题,那么请考虑将问题标记为重复,而不是发布答案。
    【解决方案3】:

    试试这个:

    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    #include <iostream>
    using namespace std;
    
    int main () {
    
       int i = 0;
       char load[26];
       while(i<25) {
           system("cls");
           load[i++] = '|';
           load[i] = '\0';
    
           printf("\n\nLOADING [%-25s]", load);
           usleep(199900);
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多