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
精彩评论