C++實現簡單的計時器
阿新 • • 發佈:2019-02-20
#include <iostream> #include <cstdlib> #include <ctime> #include <conio.h> #include <iomanip> #include <windows.h> using namespace std; void gotoxy(int x, int y)//定位游標,x為行座標,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;//賦1為顯示,賦0為隱藏 SetConsoleCursorInfo(hOut,&cci); } class Timer { private: long start_time; long pause_time; //兩個bool值標記四種狀態 bool is_pause; //記錄計時器的狀態 (是否處於暫停狀態) bool is_stop;//是否處於停止狀態 public: Timer(); bool isPause(); //返回計時器狀態 bool isStop(); //計時器的三種動作(功能) void Start(); void Pause(); void Stop(); inline long getStartTime() {return start_time;} void show(); }; Timer::Timer() { is_pause = false; //初始化計時器狀態 is_stop = true; } bool Timer::isPause() { if(is_pause) return true; else return false; } bool Timer::isStop() { if(is_stop) return true; return false; } void Timer::Start() //開始 { if(is_stop) { start_time = 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 = 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; } } void Timer::show() { long t = time(0) - start_time; gotoxy(35,12); cout<<setw(2)<<setfill('0')<<t/60/60<<":" <<setw(2)<<setfill('0')<<t/60<<":" <<setw(2)<<setfill('0')<<t%60<<endl; } int main() { Timer t; char ch; hidden();//隱藏游標 system("color 02"); gotoxy(35,12); cout<<"00:00:00"; gotoxy(20,18); 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(); } } }