问题描述
我想显示一个进度条,但是将打印代码放在一个单独的函数中似乎会调用 std::flush,因为每次进度条在新行中打印时。内联使用代码时没有发生这种情况 代码:
#include <iostream>
#include <unistd.h>
void load(int curr,int total) {
std::cout << "\n[";
int pos = 50 * curr/total;
for (int i = 0; i < 50; ++i) {
if (i < pos) std::cout << "=";
else if (i == pos) std::cout << ">";
else std::cout << " ";
}
std::cout << "]" << int(float(curr)/(float)total * 100.0) << " %\r";
std::cout.flush();
}
int main(){
for( int i = 0; i <= 5; i++ ){
load(i,5);
}
std::cout << std::endl;
return 0;
}
它的作用:
[> ]0 %
[==========> ]20 %
[====================> ]40 %
[==============================> ]60 %
[========================================> ]80 %
[==================================================]100 %
它应该做什么:在同一行打印所有内容
解决方法
函数中的第一行输出 \n
,这使得它每次迭代都在新行上打印。
修复:
#include <iostream>
void load(int curr,int total) {
std::cout << '[';
int pos = 50 * curr/total;
for (int i = 0; i < 50; ++i) {
if (i < pos) std::cout << '=';
else if (i == pos) std::cout << '>';
else std::cout << ' ';
}
std::cout << ']' << int(float(curr)/(float)total * 100.0) << " %\r" << std::flush;
}
int main(){
for( int i = 0; i <= 5; i++ ){
load(i,5);
}
std::cout << '\n';
}