c - 枚举和一个以字符串形式返回月份名称的函数

标签 c enums switch-statement

这是练习:

Write a function called monthName() that takes as its argument a value of type enum month (as defined in this chapter) and returns a pointer to a character string containing the name of the month. In this way, you can display the value of an enum month variable with a statement such as:

printf("%s\n", monthName(aMonth));

我编写了我的版本并获得了预期的输出。但是,我确信必须有更好的方法来实现这一点,而不必每个月都使用一个 case 的 switch 语句。我怎样才能用更好的设计来编写这个函数?

#include <stdio.h>

enum month { January = 1, February, March, April, May, June, 
        July, August, September, October, November, December };

char *monthName(enum month m){
    switch (m) {
        case January:
            return "January";
            break;
        case February:
            return "February";
            break;
        case March:
            return "March";
            break;
        case April:
            return "April";
            break;
        case May:
            return "May";
            break;
        case June:
            return "June";
            break;
        case July:
            return "July";
            break;
        case August:
            return "August";
            break;
        case September:
            return "September";
            break;
        case October:
            return "October";
            break;
        case November:
            return "November";
            break;
        case December:
            return "December";
            break;
        default:
            return "Not a valid month";
    }
}

int main(void)
{
    enum month aMonth = 1;

    printf("%s\n", monthName(aMonth));

    aMonth = 2;
    printf("%s\n", monthName(aMonth));

    aMonth = 6;
    printf("%s\n", monthName(aMonth));

    return 0;
}

最佳答案

您可以使用一个简单的查找表,因为枚举以 1 开头:

#include <stdio.h>

enum month { January = 1, February, March, April, May, June, 
        July, August, September, October, November, December };

const char *months_str[] = {
    "January", "February", "March", "April", "May", "June", "July",
    "August", "September", "October", "November", "December", NULL
};

const char *monthName(enum month m) {
    if(m < January || m > December)
        return "Invalid month";

    return months_str[m-1];
}

int main(void)
{
    enum month aMonth = 1;

    printf("%s\n", monthName(aMonth));

    aMonth = 2;
    printf("%s\n", monthName(aMonth));

    aMonth = 6;
    printf("%s\n", monthName(aMonth));

    return 0;
}

关于c - 枚举和一个以字符串形式返回月份名称的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49438423/

相关文章:

java - 如何使用 Spring 在枚举构造函数中注入(inject)参数?

c# - 不在循环内执行switch语句,并且循环不循环

c - 使用 struct 和 switch 的意外循环

c++ - 将 QVariant 中的枚举转换为整数

c++ - 在 C++ 中使用枚举作为数组索引

c# - 为什么在 C# 中,在默认情况下切换循环中需要 break?

c++ - 数组奇怪的参数调理

c - 如何在 C 中的结构中存储可变长度数组

c - 如何解析JS发送给C的C中字典的Dictionary?

C程序在本地运行良好,但在远程服务器上出现段错误