c - C 中枚举与 switch-case 的使用

标签 c enums switch-statement scanf

#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/

相关文章:

c - 为什么这个数组现在不能正确输出,即使它在早期的测试中工作得很好

c - 带有头文件和椅子的 3 维数组

c# - 使用 using 指令在 C# 中缩短带有别名的枚举声明

Java 多个 switch 语句 - NoSuchElementException

java - 如何对没有参数的 void 方法进行单元测试

c# - 在编译时为 switch case 生成 const 字符串

c - C 中的数组问题

C char 数组、指针、malloc、free

mysql - MySQL 中是否有一个函数不允许在已经从数据库中的 ENUM 数据类型中选择一个值之后直接选择一个值?

C# 枚举解析和反射