C++ Windows環境實現時鐘類
阿新 • • 發佈:2018-11-25
注意VS2017環境和其他環境略有不同
#include<iostream> #include<time.h> #include<Windows.h> #include<iomanip> using namespace std; class Clock { public: Clock() { struct tm tp; //tm結構指標 time_t now; //宣告time_t型別變數 time(&now); //獲取系統日期和時間 localtime_s(&tp, &now); //獲取當地日期和時間 _hour = tp.tm_hour; _min = tp.tm_min; _sec = tp.tm_sec; } void run() { while (1) { tick(); display(); } } void tick() { Sleep(1000); if (++_sec == 60) { _sec = 0; if (++_min == 60) { _min = 0; if (++_hour == 24) { _hour = 0; } } } } void display() { system("cls"); /*cout <<setfill("0")<<setw(2)<< _hour << ":"<< setw(2) << _min << ":"<< setw(2) << _sec << endl;*/ printf("%02d:%02d:%02d\n", _hour, _min, _sec); } private: int _hour; int _min; int _sec; }; int main() { Clock c; c.run(); }