【问题标题】:Time of clock is not updating in c++时钟时间没有在 C++ 中更新
【发布时间】:2014-10-02 08:03:31
【问题描述】:
#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

【问题讨论】:

  • 请编辑您的问题以更好地缩进您的代码。您在哪个硬件、哪个操作系统、哪个编译器和编译选项上运行它?你知道strftime(3) & &lt;chrono&gt; 吗?您编译时是否包含所有警告和调试信息 (g++ -Wall -g)?您是否使用过调试器 (gdb)?
  • 您可能缺少一些#include 指令。 time(2)你需要的文件#include &lt;time.h&gt;
  • 这对我来说很好用(在固定大括号之后)。
  • 我编辑了代码,我知道 strftime 和 但我想它们都不会帮助我更新时间。
  • 我正在使用带有代码块编译器的 Windows 7。

标签: c++ date time


【解决方案1】:

您需要每隔一定时间清除控制台并再次显示日期。

考虑以下示例(使用 -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;
}

在给定的代码中,我们无限循环以下代码:

  1. 清除控制台
  2. 回复cout日期
  3. 等待1000ms (1s)

【讨论】:

  • 在代码块中,你可以通过Settings启用c++11(使用&lt;chrono&gt;) > Compiler Settings > Compiler Settings > Global compiler settings > Compiler settings > Compiler flags > 检查Have g++ follow the C++11 ISO C++ language standard > OK.
  • 喜欢您的工作,感谢 stackoverflow 的快速响应。
猜你喜欢
  • 2012-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-20
  • 1970-01-01
  • 1970-01-01
  • 2019-05-31
相关资源
最近更新 更多