这是练习:
编写一个名为
monthName()
的函数,该函数将类型enum month
的值作为其参数(如本章中所定义),并返回指向包含月份名称的字符串的指针。通过这种方式,您可以使用以下语句显示enum month
变量的值:
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;
}
答案 0 :(得分:5)
您可以创建一个包含字符串的数组,并使用枚举对其进行索引。
const char *monthNames[] = { "Not a valid month", "January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November" "December" };
const char *monthName(enum month m)
{
if (m < 1 || m > 12) {
return monthNames[0]; // string for invalid month
} else {
return monthNames[m];
}
}
答案 1 :(得分:5)
您可以使用简单的查找表,因为枚举以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;
}
答案 2 :(得分:0)
开关很好(但在break
之后删除了return
,它们是无法到达的噪音),但阵列可以更简单。
在C99及以上版本中,您可以使用枚举符号使其超级清晰(理论上使得字符串的源代码顺序无关紧要):
const char *monthName(month m)
{
static const char * const names[] = {
[January] = "January",
[February] = "February",
... and so on ...
};
return names[m];
}
数组static
只能初始化一次,当然const
因为它没有变化。它在函数内部,以避免乱丢顶层空间,但名称仅在该函数内部使用。
int a[] = { [99] = 4 };
仍然是100个整数的数组。