我想知道如何从用户“今天”将枚举值获取到枚举变量中,而不是像给定示例中那样通过初始化它。 我是否必须使用 scanf 来字符串数组并使 Today = 字符串数组?
#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;
}
最佳答案
这对于普通的枚举
来说是不可能的。一个经典的技巧是使用 const char* 数组来扩充枚举,其中以与枚举相同的顺序存储名称。然后,您可以使用枚举值作为数组的索引来检索相应的字符串
值。
// 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);
关于c - 从用户获取枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22177098/