制作一个控制台进度条?(Windows)

7

我有一个函数(或者说,稍后会把它变成一个函数),可以在控制台窗口中显示随机的百分比进度,就像这样:

#include <iostream>
#include <time.h>
#include <cmath>
#include <windows.h>

using namespace std;

int main()
{
    srand(time(0));
    int x = 0;

    for(int i = 0; i<100; i++){
        int r = rand() % 1000;
        x++;
        cout << "\r" << x << "% completed." << flush;
        if(i < 43){
           Sleep(r/6);
        }else if(i > 43 && i < 74){
           Sleep(r/8);
        }else if(i < 98){
           Sleep(r/5);
        }else if(i > 97 && i != 99){
           Sleep(2000);
        }
    }

    cout << endl << endl << "Operation completed successfully.\n" << flush;
    return 0;
}

事情是这样的,我希望输出结果像这样:
1% completed

|

(later...)

25% completed

|||||||||||||||||||||||||

我该怎么做呢?

提前感谢!


你不能用两行来展示进度条,那么在一行内如何展示呢?例如:“X%已完成|||||”、“XX%已完成||||||||||”。 - Mats Petersson
3个回答

15

打印字符'\r'很有用。它将光标放在行的开头。

由于您无法再访问上一行,您可以像这样使用:

25% completed: ||||||||||||||||||

每次迭代后:

int X;

...

std::cout << "\r" << percent << "% completed: ";

std::cout << std::string(X, '|');

std::cout.flush();

此外,您还可以使用:可移植文本控制台操作器


谢谢,它有效!但是没有办法分成两行吗? - Adam
哦,但由于某种原因,它破坏了百分比计数器...在达到66%后,当它到达控制台边缘时,它会继续在新行上打印出已完成的百分比。 - Adam
尽量避免|符号超过行长度的数量。 - masoud
没有用户会数一百个竖杠字符。通过显示完整范围,例如 |||*****,使其明显和简单。 - Hans Passant
尝试在每完成20%时打印一个 |。更改 | 到百分比完成的比率以适应您的需求。 - Thomas Matthews
使用std::cout << std::string( X, '|' );代替for - Boris

0

我认为这样看起来更好:

#include <iostream>
#include <iomanip>
#include <time.h>
#include <cmath>
#include <windows.h>
#include <string>

using namespace std;
string printProg(int);

int main()
{
    srand(time(0));
    int x = 0;
    cout << "Working ..." << endl;
    for(int i = 0; i<100; i++){
        int r = rand() % 1000;
        x++;
        cout << "\r" << setw(-20) << printProg(x) << " " << x << "% completed." << flush;
        if(i < 43){
           Sleep(r/6);
        }else if(i > 43 && i < 74){
           Sleep(r/8);
        }else if(i < 98){
           Sleep(r/5);
        }else if(i > 97 && i != 99){
           Sleep(1000);
        }
    }

    cout << endl << endl << "Operation completed successfully.\n" << flush;
    return 0;
}

string printProg(int x){
    string s;
    s="[";
    for (int i=1;i<=(100/2);i++){
        if (i<=(x/2) || x==100)
            s+="=";
        else if (i==(x/2))
            s+=">";
        else
            s+=" ";
    }

    s+="]";
    return s;
}

-1
使用 graphics.h 或者使用更先进的 WinBGI 库。下载并将库文件和 graphics.h 文件放置在项目的适当位置。然后只需使用名为 gotoxy(int x, int y) 的函数,其中 x 和 y 是以字符位置(而不是像素)表示的。将您的控制台窗口视为笛卡尔坐标系的第四象限。但是 x 和 y 通常从 1 开始,最大值取决于控制台窗口的大小。每次发生进度时只需要清除屏幕即可。
    system("cls");   

在Windows中,cls是该命令。否则,在Linux/Mac中使用

    system("clear");

现在这个函数在stdlib.h头文件中。之后你可以轻松更新进度条并在其中任何位置写入。 但是你正在使用的进度条是不连续的。更有效的方法是使用

# Print iterations progress
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█'):
    """
    Call in a loop to create terminal progress bar
    @params:
        iteration   - Required  : current iteration (Int)
        total       - Required  : total iterations (Int)
        prefix      - Optional  : prefix string (Str)
        suffix      - Optional  : suffix string (Str)
        decimals    - Optional  : positive number of decimals in percent complete (Int)
        length      - Optional  : character length of bar (Int)
        fill        - Optional  : bar fill character (Str)
    """
    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = '\r')
    # Print New Line on Complete
    if iteration == total: 
        print()

# 
# Sample Usage
# 

from time import sleep

# A List of Items
items = list(range(0, 57))
l = len(items)

# Initial call to print 0% progress
printProgressBar(0, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
for i, item in enumerate(items):
    # Do stuff...
    sleep(0.1)
    # Update Progress Bar
    printProgressBar(i + 1, l, prefix = 'Progress:', suffix = 'Complete', length = 50)

# Sample Output
Progress: |█████████████████████████████████████████████-----| 90.0% Complete

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接