#include <ctime>
#include <iostream>
using namespace std;
int main() {
time_t t = time(0); // get time now
struct tm * now = localtime( & t );
cout << now->tm_mday << '-'//day
<< (now->tm_mon +1 ) << '-'//month
<< (now->tm_year +1900 )//year
<<endl
<<now->tm_hour//hour
<<'-'<<now->tm_min//min
<<'-'<< now->tm_sec//sec
<< endl;
return 0;
}
这段代码给了我系统日期和时间,我唯一的问题是时间没有更新。
例如:=时间没有向前移动并且停留在固定时间,如1.33.10
答案 0 :(得分:0)
您需要清除控制台并在每个给定的时间内再次显示日期。
请考虑以下示例(使用-std=c++11
编译):
#include <iostream> // IO
#include <ctime> // time
#include <thread> // threads
#include <chrono> // chrono
int main(){
while(true){
system("clear"); // clear console
time_t t = time(0); // get time now
struct tm* now = localtime(&t);
std::cout << now->tm_mday << '-' // day
<< (now->tm_mon + 1) << '-' // month
<< (now->tm_year + 1900) << std::endl // year
<< now->tm_hour << '-' // hour
<< now->tm_min << '-' // min
<< now->tm_sec << std::endl // sec
;
// sleep for 1000 ms (=1s)
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
return 0;
}
在给定的代码中,我们无限循环代码:
cout
日期1000ms
(1s
)