从用户获取枚举值

时间:2014-03-04 16:10:26

标签: c enums

我想知道如何将枚举值从用户获取到“今天”的枚举变量中,而不是像在给定示例中那样初始化它。 我是否必须使用scanf来串联数组并使today = string array?

#include <stdio.h>
enum week{ sunday, monday, tuesday, wednesday, thursday, friday, saturday};
int main(){
enum week today;
today=wednesday;
printf("%d day",today+1);
return 0;
} 

3 个答案:

答案 0 :(得分:1)

使用普通enum无法做到这一点。一个经典的技巧是使用array of const char*来增加枚举,其中您以与枚举相同的顺序存储名称。然后,您可以使用枚举值作为数组的索引,以检索相应的string值。

// enum to string
printf("%s\n", week_str[MONDAY]);
// string to enum
const char* input = "tuesday"; // get this from scanf or something
size_t length = strlen(input);
int i;
int found = -1;
for (i = 0; i <= WEDNESDAY; i++) {
  if(strncmp(input, week_str[i], length) == 0) {
    found = i;
    break;
  }
}
printf("Found: %i", found);

答案 1 :(得分:0)

是或多或少。枚举在内部表示为整数,枚举类型的名称在编译期间丢失。

您的程序将打印

4 day

如果要保留日期的名称,则必须使用字符串数组,例如

const char *days[] =
{
  "sunday", "monday", "tuesday", "wednesday", ...
} ;

自己做转换。例如:

printf ("The day is %s", days[monday]) ;

将打印

The day is monday

答案 2 :(得分:0)

我会这样做:

#include <stdio.h>
#include <ctype.h>

enum week{ sunday, monday, tuesday, wednesday, thursday, friday, saturday };

char * EnumToString(int day)    {
    switch (day)    {
        case sunday: return "sunday";
        case monday: return "monday";
        case tuesday: return "tuesday";
        case wednesday: return "wednesay";
        case thursday: return "thursday";
        case friday: default: return "friday";
    }
}

enum week StringToEnum(char * day)  {

    // To not be case sensitive
    for(int i = 0; str[i]; i++){
      day[i] = tolower(day[i]);
    }
    switch (day)    {
        case "sunday": return sunday;
        case "monday": return monday;
        case "tuesday": return tuesday;
        case "wednesday": return wednesay;
        case "thursday": return thursday;
        case "friday": default: return friday;
    }
}

int main(){
    enum week today;
    today=wednesday;
    printf("%dth day is %s",today+1, EnumToString(today+1));
    return 0;
} 

它将打印:

4th day is thursday