我是用C++在Linux下编制的标准。在我的节目我想添加一个简单的时钟显示HH:MM:SS。什么是最简单的方式做到这一点吗?

有帮助吗?

解决方案

一个好方法是使用本地时间

其他提示

你可以使用 localtime 随着 strftime.

工作链接

我的快速和脏溶液:

// file now.cc
#include <iostream>
#include <iomanip>
#include <ctime>

using namespace std;

int main()
{
    time_t ct = time(0);
    struct tm* currtime = localtime(&ct);
    cout << setfill('0') << setw(2) << currtime->tm_hour << ":"
         << setw(2) << currtime->tm_min << ":"
         << setw(2) << currtime->tm_sec << endl;
    return 0;
}

此也做补零(这你可能想)。

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void delay(unsigned int mseconds)
{
    clock_t goal = mseconds + clock();
    while (goal > clock());
}
int main()
{
    time_t myTime;

    while(1)
    {
        time(&myTime);
        printf("%s", asctime(gmtime(&myTime)));
        delay(1000);
        system("cls");
    }
    return 0;
}

最简单方式?

system("date +%T");

看看getTimeStamp() 你可以调整这个给你想要的任何格式

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top