#include <iostream>
#include <time.h>
#include <iomanip>
#include <unistd.h>
#include <stdlib.h>
using namespace std;
class Clock{
public:
Clock(){
time_t t = time(NULL);
//返回当前的时间戳,从(格林威治时间1970年1月1日00:00:00)到当前时间的秒数
struct tm *ti = localtime(&t); //tm结构体是time.h中定义的用于分别存储时间的各个量(年月日等)的结构体
hour = (*ti).tm_hour;
min = (*ti).tm_min;
sec = (*ti).tm_sec;
}
void run(){
while(1){
show();//完成显示
tick();//数据更新
}
}
private:
void show(){
system("clear");//执行shell 命令
cout<<setw(5)<<setfill('0')<<hour<<":";
cout<<setw(2)<<setfill('0')<<min<<":";
cout<<setw(2)<<setfill('0')<<sec<<endl;
}
void tick(){
sleep(1);
if(++sec == 60){
sec = 0;
min += 1;
if(++min == 60){
min = 0;
hour += 1;
if(hour == 24){
hour = 0;
}
}
}
}
int hour;
int min;
int sec;
};
int main(){
Clock c;
c.run();
return 0;
}
C ++: achieve clock
Guess you like
Origin blog.csdn.net/yangjinjingbj/article/details/104056346
Recommended
Ranking