【问题标题】:typedef enum to typedefstructtypedef 枚举到 typedefstruct
【发布时间】:2016-11-30 00:57:32
【问题描述】:

我想将 typedef 枚举日期保存到 typedef 结构数据中。

我的代码是

typedef enum weather {
    clear = 1,
    cloudy,
    cold,
    rainy,
    stormy
}Weather;



typedef struct diary {
    time_t date;
    Weather weather;
    char contents[MAX];
}Diary;

void save(FILE *pFile, Diary*da) {

    fprintf(pFile, " %s %s \n",da->date,da->contents);
}


void in(Diary*da) {
    int _weather;

    puts("Enter the current date(YYYY-MM-DD) : ");
    scanf("%s", &da->date);
    getchar();

    puts("Enter the current weather, (1) Clear (2) Cloudy (3) Cold (4) Rainy (5) Stormy : ");
    scanf("%d", &_weather);
    getchar();

    puts("Enter the contents");
    scanf("%79s", da->contents);
    getchar();

}

我不知道如何将数字更改为单词(晴天、阴天、寒冷..)并在输出文件中打印出来。

“time_t”数据类型到底是什么? 我无法打印出我输入的日期。

【问题讨论】:

  • “如何将数字更改为单词”。 switch (_weather)?这是一个基本的方法。更聪明的方法是使用从输入数字派生的索引的字符串数组(即查找表)。
  • 您的所有问题都在您的 C 书中进行了描述。目前尚不清楚您的具体问题是什么。阅读How to Ask 并遵循建议。并且以下划线开头的名称保留用于实现。不要使用它们。
  • 然后尝试搜索(它是免费的)。 How to print time_t in a specific format?
  • 您可能需要查找“指定初始化程序”和“x-macros”(文档中有关于 X-Macros 的文档,尽管那里还有改进的余地)。

标签: c enums


【解决方案1】:

Kaylum 在您帖子下的评论中提到了这一点,这就是建议的内容:

const char* const WEATHER_STRINGS[5] = { "Clear", "Cloudy", "Cold", "Rainy", "Stormy" };

const char* getWeatherName(int weatherIdx)
{
   return WEATHER_STRINGS[weatherIdx];
}

然后你可以这样调用函数:

getWeatherName(&da->weather)

这将返回与枚举的整数值匹配的单词。

我的 c 可能有点生锈,但这个想法是合理的,只需验证我的语法。 =)

这个想法是您创建一个数组以用作您的字符串/值的查找。然后你可以使用你的枚举作为索引从数组中提取匹配的单词。您不需要该函数,如果需要,可以直接从数组中提取,但是用函数封装它会使其更具可读性,如果以后需要更多功能,您可以随时扩展它。

至于time_t,您可以查看之前回答的问题以获取更多信息:How to print time_t in a specific format?

【讨论】:

    猜你喜欢
    • 2015-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多