2010-10-23 55 views
2

我在Linux下使用C++编译标准GCC。在我的程序中,我想添加一个显示HH:MM:SS的简单时钟。最简单的方法是什么?在C++和Linux中显示时钟的最简单方法

+0

使用std ::时间(0),然后通过转换自1970年1月1日至HH的秒数:MM:SS :))) )开玩笑吧 – 2010-10-23 20:45:46

回答

1

我的快速和肮脏的解决方案:

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

这也不会补零(这你可能想)。

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; 
} 
+0

'cls'命令是什么包?我没有,在一个相当典型的Debian安装。 – 2015-09-25 11:13:00

+0

cls简单明了,如果你在linux上打电话清除工作 – 2015-09-25 20:24:32

0

最简单的方式?

system("date +%T");