开发者

Simplest way to show a clock in C++ and Linux

I'm using C++ under Linux compiling with standard GCC. In my program I wan开发者_运维问答t to add a simple clock showing HH:MM:SS. What's the easiest way to do that?


You can make use of localtime along with strftime.

Working link


A good way is to use localtime


My quick-and-dirty solution:

// 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;
}

This also does zero-padding (which you probably want).


#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;
}


The easiest way?

system("date +%T");


Look at getTimeStamp() you can adjust this to any format you want

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜