#include <stdio.h>
#include <stdlib.h>
enum gender {male, female};
int main () {
enum gender choice;
printf("Your gender: ");
scanf("%u", &choice);
switch(choice)
{
case male: printf("You're a man."); break;
case female: printf("You're a woman."); break;
default: printf("Try again.");
}
return 0;
}
我向控制台写什么并不重要,它会向我显示“男性”情况,“你是一个男人。”。我尝试用引号和单引号编写案例,但它不起作用。你能帮助我吗?这是我的第一个问题,如果我有任何错误,我也很抱歉我的英语。
最佳答案
来自 C 标准(6.7.2.2 枚举说明符)
4 Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined,128) but shall be capable of representing the values of all the members of the enumeration.
这意味着枚举类型的对象在内部不需要存储为 int 或 unsigned int 类型的对象。它可以在内部存储为 char 类型的对象。
所以这次调用 scanf
scanf("%u", &choice);
调用未定义的行为。
您需要使用 unsigned int 类型的中间变量,并在使用此变量调用 scanf 后将其整数值分配给对象选择。
另一种方法是声明一个 char 类型的对象,并要求用户输入“m”(代表男性)或“f”(代表女性),然后您可以将其转换为值 0 或 1。
例如
char c = 0;
scanf( "%c", &c );
if ( c == 'm' ) c = 0;
else if ( c == 'f' ) c = 1;
else c = 2;
choice = c;
关于c - C 中枚举与 switch-case 的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69813368/