【问题标题】:Simplest way to show a clock in C++ and Linux在 C++ 和 Linux 中显示时钟的最简单方法
【发布时间】:2011-04-29 16:34:15
【问题描述】:

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

【问题讨论】:

  • 使用 std::time(0) 然后将自 1970 年 1 月 1 日以来经过的秒数转换为 HH:MM:SS :)))) 开个玩笑

标签: c++ linux gcc time clock


【解决方案1】:

您可以使用localtimestrftime

Working link

【讨论】:

    【解决方案2】:

    一个好办法是使用localtime

    【讨论】:

      【解决方案3】:

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

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

      这也做零填充(你可能想要)。

      【讨论】:

        【解决方案4】:
        #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;
        }
        

        【讨论】:

        • cls 命令在什么包中?我没有,在相当典型的 Debian 安装中。
        • cls 很简单,如果你在 linux 上调用 clear 就可以了
        【解决方案5】:

        最简单的方法?

        system("date +%T");
        

        【讨论】:

          【解决方案6】:

          Look at getTimeStamp()您可以将其调整为您想要的任何格式

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-01-15
            • 2011-05-20
            • 2015-08-27
            • 2016-03-15
            • 2021-08-02
            • 2011-01-17
            • 1970-01-01
            相关资源
            最近更新 更多