【问题标题】:Error in C++ time structuresC++ 时间结构中的错误
【发布时间】:2015-11-30 14:17:15
【问题描述】:

我正在创建一个程序来保存当天的天气信息。运行代码后,我得到 struct tm redefined 错误。我使用 Visual c++ 2008 作为编译器在代码块中运行它

这是我的代码:

#include<stdio.h>
#include<string.h>
#include<time.h>

struct tm  //date template
    {
        int tm_mday //day of month
        int tm_mon; //month of year
        int tm_year; //year
        //char date[11];
    };

    struct weather
    {
        struct tm *wdate1;
        int high_temp;
        int low_temp;
        int max_wind_speed;
        int preciption;
        char note[80];
    };


int main()
{
    time_t wdate;
    struct weather info[3];

    ctime(&wdate);

    printf("%s",wdate);

    return 0;
}

【问题讨论】:

  • "运行代码后" -> "编译代码后"。编译时错误和运行时错误之间的巨大差异。

标签: c++ pointers time user-defined-functions


【解决方案1】:

这是因为您正在重新定义一个已在 time.h 中使用相同名称“tm”定义的结构。如果您尝试使用相同的结构名称重新定义此模板,请不要导入

 #include <time.h>

同样在 struct tm 中,您在 tm_mday 和命令之后缺少一个终止符

 printf("%s",wdate);

将导致错误,因为 wdate 不是 char *。您应该将最后两行标记为

 printf("%s",ctime(&wdate));

希望这会有所帮助!

【讨论】:

  • 稍作修改,我建议:#include &lt;ctime&gt;
  • @LeFlou :是的,我们必须在 std 命名空间中包含
【解决方案2】:

重新定义 struct tm - 就像错误消息所说的那样 - 正是您正在做的事情。 tm 结构在 time.h 中定义。您在第 5-11 行再次定义它。如果您想定义一个自定义结构供您自己使用,您应该删除此定义,或者将其命名为不同的名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 2017-10-03
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多