#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; }
自己写了一个定时器
最新推荐文章于 2024-03-29 16:37:35 发布