1.代码
/// <summary>
/// 更新进度条
/// </summary>
/// <param name="progress">进度(0-1)</param>
void showProgress(float progress)
{
if (progress > 1)
{
progress = 1;
}
int pa = progress * 50;
std::cout << "\33[1A"; // 终端光标向上移动一行
std::cout << "[" + std::string(pa, '=') + ">" + std::string(50 - pa, ' ') << "] " << progress * 100 << "%" << std::endl;
fflush(stdout); // 刷新缓冲区
}
void print_process(float fValue, string strName = "mini", bool flag = false)
{
if (0 > fValue || fValue > 1)
{
return;
}
fValue = fValue * 100;
cout << setiosflags(ios::fixed) << setprecision(2); // 设置出书的小数后精度为2
string tag = "[" + strName + "]" + "process:" + string((fValue / 10), '*') + "[";
// flush擦除,\r定位到行首
cout << flush << '\r' << tag << fValue << "%]";
if (fValue >= 100)
{
cout << std::endl;
}
if (flag)
{
usleep(1000); // 1000us
}
}
2.测试
int main()
{
for (int i = 1; i < 101; i++)
{
float progress = i * 1.0 / 100;
showProgress(progress);
}
return 0;
}
3.效果
[==================================================>] 100%