问题
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