在C++控制台程序中实现一个简单的进度条效果通常涉及使用控制台输出和控制台光标移动。
以下是一个基本的进度条实现示例:
#include <iostream>
#include <chrono>
#include <thread>
void showProgressBar(int progress, int total) {
const int barWidth = 50;
float ratio = static_cast<float>(progress) / total;
int barLength = static_cast<int>(ratio * barWidth);
std::cout << "[";
for (int i = 0; i < barWidth; ++i) {
if (i < barLength) {
std::cout << "=";
} else {
std::cout << " ";
}
}
std::cout << "] " << static_cast<int>(ratio * 100.0) << "%\r";
std::cout.flush();
}
int main() {
const int total = 100;
for (int i = 0; i <= total; ++i) {
showProgressBar(i, total);
std::this_thread::sleep_for(std::chrono::milliseconds(50)); // 模拟一些工作
// 在实际应用中,这里可以是一些处理任务的代码
// 例如:
// 进行文件处理、数据处理等操作
// 注意:在实际应用中,进度条的显示应该与任务的进度相关联
}
std::cout << std::endl << "任务完成" << std::endl;
return 0;
}