注意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();
}