简体   繁体   English

制作控制台进度条? (视窗)

[英]Making a console progress bar? (Windows)

So I have a function (or rather, I'll turn it into a function later) to make a random % progress in a console window; 所以我有一个函数(或者更确切地说,我稍后将其转换为函数)以在控制台窗口中进行随机%进度; like this: 像这样:

#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;
}

The thing is, I want the output to be like this: 问题是,我希望输出如下:

1% completed

|

(later...) (后来...)

25% completed

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

How can I do that? 我怎样才能做到这一点?

Thanks in advance! 提前致谢!

Printing character '\\r' is useful. 打印字符'\\r'很有用。 It puts the cursor at the beginning of the line. 它将光标放在行的开头。

Since you can not access to previous line anymore, you can have something like this: 由于您无法再访问上一行,您可以使用以下内容:

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

After each iteration: 每次迭代后:

int X;

...

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

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

std::cout.flush();

Also, you can use: Portable text based console manipulator 此外,您可以使用: 基于便携式文本的控制台操纵器

I think this looks better: 我认为这看起来更好:

#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;
}

Use graphics.h or use more advanced WinBGI library. 使用graphics.h或使用更高级的WinBGI库。 Download it and place the library files and the graphics.h file in appropriate locations in your project. 下载它并将库文件和graphics.h文件放在项目的适当位置。 Then just use the function named gotoxy(int x, int y) where x and y are in character places(not pixels) Consider your console window in the 4th quadrant of a Cartesian 2D axes system. 然后只使用名为gotoxy(int x,int y)的函数,其中x和y在字符位置(不是像素)考虑在笛卡尔2D轴系统的第四象限中的控制台窗口。 But x and y starts typically from 1 upto n(depending on the size of the console window). 但是x和y通常从1到n开始(取决于控制台窗口的大小)。 You just have to clear the screen each time progress happens like this 每次进行此类操作时,您只需清除屏幕即可

    system("cls");   

as cls is the command for this in case of windows. 因为cls是windows的命令。 Otherwise for linux/Mac use 否则为linux / Mac使用

    system("clear");

Now this function is in stdlib.h header. 现在这个函数在stdlib.h头文件中。 After that you can easily update the progress bar and write anywhere in it. 之后,您可以轻松更新进度条并在其中的任何位置书写。 But the progress bar you are using is discontinuous. 但是你使用的进度条是不连续的。 There is more efficient way is to use 有更有效的方法是使用

# 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM