示意图
新建类Timer
Timer.h
#pragma once
#include <stdio.h>
#include <tchar.h>
#include <time.h>
#include <iostream>
#include <iomanip>
#include <windows.h>
class Timer
{
public:
Timer();
~Timer();
private:
long start_time;//开始的时间
long pause_time;//暂停的时间
bool is_pause;//记录计时器的状态(是否暂停)
bool is_stop;//计时器是否停止
public:
bool isPause();//让外界获取计时器是否处于暂停状态
bool isStop();//让外界获取计时器是否处于停滞状态
void Start();//开始
void Pause();//暂停
void Stop();//停止
void show();//显示时间
void gotoxy(int x, int y);
void HideCursor();
};
Timer.cpp
#include "Timer.h"
Timer::Timer()
{
is_pause = false;//初始化计时器状态
is_stop = true;
}
Timer::~Timer()
{
}
bool Timer::isPause()
{
if (is_pause)
{
return true;
}
else
return false;
}
bool Timer::isStop()
{
if (is_stop)
return true;
else
return false;
}
void Timer::Start()
{
if (is_stop)
{
start_time = (long)time(0);
is_stop = false;
}
else if (is_pause)
{
is_pause = false;
start_time += time(0) - pause_time;
}
}
void Timer::Pause()
{
if (is_stop||is_pause)//如果处于停止/暂停状态,此动作不做任何处理,直接返回
{
return;
}
else
{
is_pause = true;
pause_time = (long)time(0);//获取暂停时间
}
}
void Timer::Stop()
{
if (is_stop)
{
return;
}
else if (is_pause)
{
is_pause = false;
is_stop = true;
}
else
{
is_stop = true;
}
}
void Timer::show()
{
long t = time(0) - start_time;
gotoxy(35, 12);
std::cout << std::setw(2) << std::setfill('0') << t / 60 / 60 << ":" \
<< std::setw(2) << std::setfill('0') << t / 60 << ":"\
<< std::setw(2) << std::setfill('0') << t % 60 << std::endl;
}
void Timer::gotoxy(int x, int y)//定位到下x,y位置
{
int xx = 0x0b;
HANDLE hOutput;
COORD loc;
loc.X = x;
loc.Y = y;
hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hOutput, loc);
return;
}
void Timer::HideCursor()
{
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO CursorInfo;
GetConsoleCursorInfo(handle, &CursorInfo);//获取控制台光标信息
CursorInfo.bVisible = false;//隐藏控制台光标
SetConsoleCursorInfo(handle, &CursorInfo);//设置控制台光标状态
}
主函数
main.cpp
#include "Timer.h"
#include <conio.h>
int _tmain(int argc, _TCHAR* argv[])
{
Timer t;
char ch;
t.HideCursor();//隐藏光标
system("color 02");
t.gotoxy(20, 18);
std::cout << "按a开始,按空格暂停,按s停止";
while (1)
{
if (_kbhit())//是否有按键
{
ch = _getch();//获取按键信息
switch (ch)
{
case 'a':
t.Start();
break;
case 's':
t.Stop();
break;
case ' ':
t.Pause();
break;
default:
break;
}
}
if ((!t.isStop())&&(!t.isPause()))
{
t.show();
}
}
return 0;
}