自己写了一个定时器


#include <iostream>
#include <time.h>
#include <conio.h>
#include <iomanip>


using namespace std;

void gotoxy(int x, int y)
{
	COORD pos = { x, y };
	HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
	SetConsoleCursorPosition(hOut, pos);
}

void hidden()
{
	HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
	CONSOLE_CURSOR_INFO cci;
	GetConsoleCursorInfo(hOut, &cci);
	cci.bVisible = 0;
	SetConsoleCursorInfo(hOut, &cci);
}

class Timer
{
public:
	Timer();
	~Timer();

	//三种状态功能
	void Start();
	void Pause();
	void Stop();
	//返回立即状态
	bool isPause() const;
	bool isStop() const;
	void show() const;
	inline long getStartTime() const { return start_time; }

private:
	long start_time;
	long pause_time;
	//用两个值来标记四种状态
	bool is_pause;
	bool is_stop;
};

Timer::Timer() : start_time(0), pause_time(0)
{
	is_pause = false;
	is_stop = true;
}

Timer::~Timer()
{
	
}

void Timer::Start()
{
	if (is_stop)
	{
		is_stop = false;
		start_time = static_cast<long>(time(0));
	}
	else if (is_pause)
	{
		is_pause = false;
		start_time += static_cast<long>(time(0)) - pause_time;
	}
}

void Timer::Pause()
{
	if (is_stop || is_pause)
		return;
	else
	{
		is_pause = true;
		pause_time = static_cast<long>(time(0));
	}
}

void Timer::Stop()
{
	if (is_stop)
		return;
	else if (is_pause)
	{
		is_pause = false;
		is_stop = true;
	}
	else if(!is_stop)
	{
		is_stop = true;
	}
	//else:
}

bool Timer::isPause() const
{
	if (is_pause)
		return true;
	else
		return false;
}

bool Timer::isStop() const
{
	if (is_stop)
		return true;
	else
		return false;
}

void Timer::show() const
{
	long t = time(0) - start_time;
	gotoxy(35, 10);
	cout << setw(2) << setfill('0') << t / 60 / 60 << ":"
		<< setw(2) << setfill('0') << t / 60 << ":"
		<< setw(2) << setfill('0') << t % 60 << endl;
}

int main(int argc, char* argv[])
{	
	Timer timer;
	hidden();
	system("color 03");
	gotoxy(35, 10);
	cout << "00:00:00";
	gotoxy(26, 15);
	cout << "按a开始, 按空格暂停,按s停止";
	while (true)
	{
		if (_kbhit())
		{
			auto ch = _getch();
			switch (ch)
			{
			case 'a':
				timer.Start();
				break;
			case ' ':
				timer.Pause();
				break;
			case 's':
				timer.Stop();
				break;
			default:
				break;
			}
		}
		if (!timer.isPause() && !timer.isStop())
		{
			timer.show();
		}
	}
	
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值