【问题标题】:tm t1 has incomplete type and cannot be definedtm t1 类型不完整,无法定义
【发布时间】:2012-01-08 11:53:00
【问题描述】:

我必须编写一个在无限循环中调用sleep(60) 的程序。通过循环每五次我必须获取当前时间并打印 tm_sec 字段。

这是我写的:

#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>

int main()
{
    struct tm t1;
    int i=0;
    for(;;)
    {
        sleep(60);
        if(i%5==0)
            {
                gettimeofday(&t1,NULL);
                printf("%d\n",t1.tm_sec);
            }
        i++;
    }
}

我收到一条错误消息,提示 aggregate tm t1 has incomplete type and cannot be defined.

我不知道我做错了什么。

【问题讨论】:

    标签: c++ unix time.h


    【解决方案1】:

    你想要的是 struct timeval,而不是 struct tm。试试这个:

    struct timeval t1;
    

    另外,你想要t1.tv_sec,而不是t1.tm_sec

    【讨论】:

    • 我必须打印 tm_sec 字段,该字段在结构 timeval 中没有定义。
    • 那就看看Kerrek的回答吧。
    • 这将使代码编译,但它不会提供与打印 tm_sec 字段相同的输出。
    【解决方案2】:

    你用错了。选择以下两项之一:

    #include <sys/time.h>
    
    int gettimeofday(struct timeval *tv, struct timezone *tz);
    int settimeofday(const struct timeval *tv, const struct timezone *tz);
    

    或者:

     #include <time.h>
    
     char *asctime(const struct tm *tm);
     struct tm *gmtime(const time_t *timep);
     struct tm *localtime(const time_t *timep);
    

    【讨论】:

    • 您必须同时选择两者才能获得当地时间(使用time()gettimeofday()),转换为tm 以获得tm_sec 字段。
    • 你的意思是微秒? time() 已经精确到秒了,不是吗?我认为gettimeofday 完全包含time,但我不确定。
    • 不,我的意思是你需要 both 一些东西来获取当前时间 并且 一些东西来将它构造成 tm。您的回答说要选择其中之一-如果没有两者,您将如何解决问题?或者你的回答应该暗示调用time()
    • @MikeSeymour:啊,当然,您需要time() gettimeofday 的秒部分才能获得gmtime 可以处理的实际时间。我有点慢。
    【解决方案3】:

    gettimeofday 采用指向 timeval 的指针,而不是 tm,给出自 1970 年以来的秒(和微秒)时间。

    如果您想要tm,则需要&lt;ctime&gt; 中的函数,例如localtime(),来转换timeval 的秒字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-06
      • 2014-05-20
      • 2021-06-24
      • 2020-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多