Adding a status bar to c++ console applications

北慕城南 提交于 2019-12-10 20:02:15

问题


I am making a linux application using C++ and it will print info out to the console. Parts of the program will take a while to compute and I would like to add a status bar in the console similar to the one used in wget (I put my own depiction below).

%complete[===========>               ] eta

What would be the best way to accomplish this goal? Are there any useful libraries that make it easy to add this functionality?


回答1:


If your program is like wget, that is, it's basically a batch program without the need for a full-screen UI (for which I would recommend ncurses), you can use the trick to print a carriage return (but not line feed) after your line; the next thing you write will overwrite the same line.

Here's a demonstration.

#include <iostream>
#include <unistd.h>

int main(void)
{

        for (int i = 0; i < 10; i++) {
                std::cout << "Status: " << i << "\r" << std::flush;
                sleep(1);
        }
        std::cout << "Completed.\n";
}



回答2:


The ncurses library should be useful to you. Or you can write the progress line char by char, using backspaces, calling fflush or std::flush, etc.

A simpler way would just to output dots...



来源:https://stackoverflow.com/questions/8200973/adding-a-status-bar-to-c-console-applications

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!