c++ 控制台 活动指标 进度条

第一版

class ProgressBar
{
public:
	void updateProgress(float value, std::ostream& os = std::cout)
	{
		set_progress(value);
		fillProgress(os);
	}

private:
	void set_progress(float value)
	{
		std::lock_guard<std::mutex> lg(mutex_);
		progress_ = value;
	}

	void fillProgress(std::ostream& os)
	{
		std::lock_guard<std::mutex> lg(mutex_);
		if (progress_ > 1.0f)
			return;

		os << "\r" << std::flush;
		os << "[";

		const auto completed = static_cast<size_t>(progress_ * bar_width_);
		for (size_t i = 0; i < bar_width_; ++i)
		{
			if (i <= completed)
				os << fill_;
			else
				os << remainder_;
		}

		os << "]";
		os << " " << static_cast<size_t>(progress_ * 100.0) << "%";
		fflush(stdout);
	}

private:
	std::mutex mutex_;

	size_t bar_width_ = 50;
	std::string remainder_ = "-";
	std::string fill_ = "▉";
	float progress_ = 0.0f;
};

第一版光标会闪烁,因此改进,完成第二版
第二版

class ProgressBar
{
public:
	void updateProgress(float value)
	{
		set_progress(value);
		fillProgress();
	}

private:
	void set_progress(float value)
	{
		std::lock_guard<std::mutex> lg(mutex_);
		progress_ = value;
	}

	void fillProgress()
	{
		std::lock_guard<std::mutex> lg(mutex_);
		if (progress_ > 1.0f)
			return;

		std::string buffer = "";

		buffer += "[";

		const auto completed = static_cast<size_t>(progress_ * bar_width_);
		for (size_t i = 0; i < bar_width_; ++i)
		{
			if (i <= completed)
				buffer += fill_;
			else
				buffer += remainder_;
		}

		buffer += "]";
		buffer += " " + to_string(static_cast<size_t>(progress_ * 100.0)) + "%";
		printf("\r%s", buffer.c_str());
		// 解决光标闪烁
		// 刷新缓冲区,将缓冲区内的数据输出到设备
		fflush(stdout);
	}

private:
	std::mutex mutex_;

	size_t bar_width_ = 50;
	std::string remainder_ = "-";
	std::string fill_ = "▉";
	float progress_ = 0.0f;
};
  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值