programing

진행률 표시기를 순수 C/C++(cout/printf)로 표시하는 방법

bestcode 2022. 9. 15. 23:58
반응형

진행률 표시기를 순수 C/C++(cout/printf)로 표시하는 방법

큰 파일을 다운로드하기 위해 콘솔 프로그램을 C++로 작성하고 있습니다.파일 크기를 알고 다운로드하기 위해 작업 스레드를 시작합니다.진행률 표시기를 보여드리고 싶어요.

다른 시간에 다른 문자열을 같은 위치에 cout 또는 printf로 표시하려면 어떻게 해야 합니까?

의 경우C프로그레스바 너비가 조정 가능한 솔루션에서는 다음을 사용할 수 있습니다.

#define PBSTR "||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"
#define PBWIDTH 60

void printProgress(double percentage) {
    int val = (int) (percentage * 100);
    int lpad = (int) (percentage * PBWIDTH);
    int rpad = PBWIDTH - lpad;
    printf("\r%3d%% [%.*s%*s]", val, lpad, PBSTR, rpad, "");
    fflush(stdout);
}

다음과 같이 출력됩니다.

 75% [||||||||||||||||||||||||||||||||||||||||||               ]

출력의 고정 너비에서는 다음과 같은 것을 사용합니다.

float progress = 0.0;
while (progress < 1.0) {
    int barWidth = 70;

    std::cout << "[";
    int pos = barWidth * progress;
    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.16; // for demonstration only
}
std::cout << std::endl;

http://ideone.com/Yg8NKj

[>                                                                     ] 0 %
[===========>                                                          ] 15 %
[======================>                                               ] 31 %
[=================================>                                    ] 47 %
[============================================>                         ] 63 %
[========================================================>             ] 80 %
[===================================================================>  ] 96 %

이 출력은 1줄씩 아래에 표시되지만 터미널 에뮬레이터(Windows 명령줄에서도 마찬가지)에서는 같은 행에 인쇄됩니다.

마지막으로, 더 많은 자료를 인쇄하기 전에 새 줄을 인쇄하는 것을 잊지 마십시오.

막대를 마지막에 제거하려면 공백으로 덮어써야 합니다. 예를 들어 다음과 같이 짧은 것을 인쇄하려면"Done.".

또, 물론, 같은 방법으로 할 수 있습니다.printf위의 코드를 쉽게 적용할 수 있습니다.

라인 피드(\n) 없이 "캐리지 리턴"(\r)을 사용할 수 있으며 콘솔이 올바르게 작동하기를 바랍니다.

제가 이 질문에 답하는 것이 조금 늦다는 것을 알지만, 저는 당신이 원하는 대로 할 수 있는 간단한 수업을 만들었습니다.(제가 쓴 것을 기억해주세요)using namespace std;를 참조해 주세요).:

class pBar {
public:
    void update(double newProgress) {
        currentProgress += newProgress;
        amountOfFiller = (int)((currentProgress / neededProgress)*(double)pBarLength);
    }
    void print() {
        currUpdateVal %= pBarUpdater.length();
        cout << "\r" //Bring cursor to start of line
            << firstPartOfpBar; //Print out first part of pBar
        for (int a = 0; a < amountOfFiller; a++) { //Print out current progress
            cout << pBarFiller;
        }
        cout << pBarUpdater[currUpdateVal];
        for (int b = 0; b < pBarLength - amountOfFiller; b++) { //Print out spaces
            cout << " ";
        }
        cout << lastPartOfpBar //Print out last part of progress bar
            << " (" << (int)(100*(currentProgress/neededProgress)) << "%)" //This just prints out the percent
            << flush;
        currUpdateVal += 1;
    }
    std::string firstPartOfpBar = "[", //Change these at will (that is why I made them public)
        lastPartOfpBar = "]",
        pBarFiller = "|",
        pBarUpdater = "/-\\|";
private:
    int amountOfFiller,
        pBarLength = 50, //I would recommend NOT changing this
        currUpdateVal = 0; //Do not change
    double currentProgress = 0, //Do not change
        neededProgress = 100; //I would recommend NOT changing this
};

사용 방법의 예:

int main() {
    //Setup:
    pBar bar;
    //Main loop:
    for (int i = 0; i < 100; i++) { //This can be any loop, but I just made this as an example
        //Update pBar:
        bar.update(1); //How much new progress was added (only needed when new progress was added)
        //Print pBar:
        bar.print(); //This should be called more frequently than it is in this demo (you'll have to see what looks best for your program)
        sleep(1);
    }
    cout << endl;
    return 0;
}

주의: 바의 외관을 쉽게 바꿀 수 있도록 클래스의 모든 문자열을 공개했습니다.

캐리지 리턴 문자를 인쇄할 수 있습니다.\r) 출력을 현재 행의 선두로 되돌립니다.

좀 더 정교한 접근법에 대해서는 ncurses(콘솔 텍스트 기반 인터페이스용 API)와 같은 것을 살펴보세요.

또 다른 방법은 도트 또는 원하는 문자를 표시하는 것입니다.아래 코드는 1초마다 진행률 표시기 [일종의 로드...]를 점으로 인쇄합니다.

추신: 저는 여기서 자고 있어요.퍼포먼스가 중요한지 다시 한 번 생각해 보세요.

#include<iostream>
using namespace std;
int main()
{
    int count = 0;
    cout << "Will load in 10 Sec " << endl << "Loading ";
    for(count;count < 10; ++count){
        cout << ". " ;
        fflush(stdout);
        sleep(1);
    }
    cout << endl << "Done" <<endl;
    return 0;
}

Boost progress_display를 확인합니다.

http://www.boost.org/doc/libs/1_52_0/libs/timer/doc/original_timer.html#Class%20progress_display

필요한 기능을 할 수 있을 것 같고, 헤더 전용 라이브러리이므로 링크할 수 없습니다.

제가 만든 간단한 것은 다음과 같습니다.

#include <iostream>
#include <thread>
#include <chrono>
#include <Windows.h>
using namespace std;

int main() {
   // Changing text color (GetStdHandle(-11), colorcode)
   SetConsoleTextAttribute(GetStdHandle(-11), 14);
   
   int barl = 20;
   cout << "[";     
   for (int i = 0; i < barl; i++) {         
      this_thread::sleep_for(chrono::milliseconds(100));
      cout << ":";  
   }
   cout << "]";

   // Reset color
   SetConsoleTextAttribute(GetStdHandle(-11), 7);
}

이 코드가 도움이 될 수도 있습니다.

#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#include <cmath>

using namespace std;

void show_progress_bar(int time, const std::string &message, char symbol)
{
    std::string progress_bar;
    const double progress_level = 1.42;

    std::cout << message << "\n\n";

    for (double percentage = 0; percentage <= 100; percentage += progress_level)
    {
        progress_bar.insert(0, 1, symbol);
        std::cout << "\r [" << std::ceil(percentage) << '%' << "] " << progress_bar;
        std::this_thread::sleep_for(std::chrono::milliseconds(time));       
    }
    std::cout << "\n\n";
}

int main()
{
    show_progress_bar(100, "progress" , '#');
}

언급URL : https://stackoverflow.com/questions/14539867/how-to-display-a-progress-indicator-in-pure-c-c-cout-printf

반응형