简体   繁体   English

将整数值分配给C中的结构内的枚举?

[英]Assigning integer values to an enumeration within a struct in C?

I am learning enums and structs right now and have a case I cannot solve. 我现在正在学习枚举和结构,并且有一个案例无法解决。 If I have a basic struct and define an employee, I see I can do the following.. 如果我有一个基本的结构并定义了一个雇员,那么我可以执行以下操作。

I have the employee added to the first item, but how can I have the user input an integer and then have that integer be assigned to Low, Medium or High using the enum nested within the struct? 我已将员工添加到第一项,但是我如何让用户输入一个整数,然后使用嵌套在结构中的枚举将该整数分配给Low,Medium或High? Thanks! 谢谢!

struct add {

    char employee[255];
    enum EmployeeLevel {Low = 0, Medium, High};
};

struct add EMP[10]; //Global variable to add employees using the add struct

printf("Please enter employee name\n");
scanf("%s", EMP[0].employee); //Assigns the user input to the name of the first employee

It may be off, but you could do something like this: 可能关闭了,但是您可以执行以下操作:

enum EmployeeLevel {Low = 0, Medium, High};  //declare the enum outside the struct


struct add {

    char employee[255];
    enum EmployeeLevel level;                //create a variable of type EmployeeLevel inside the struct
};

struct add EMP[10]; //Global variable to add employees using the add struct

printf("Please enter employee name\n");
scanf("%s", EMP[0].employee); //Assigns the user input to the name of the first employee
scanf("%d", EMP[0].level); //Assings a level to the corresponding employee

This just cannot work. 这根本行不通。 scanf would need to know the size of the item that it is reading in bytes. scanf将需要知道它正在读取的项目的大小(以字节为单位)。 However, C doesn't define that size for an enum. 但是,C没有为枚举定义该大小。

Create a temporary variable of type int, scanf into that variable, then assign it to the enum. 创建一个int类型的临时变量,将scanf放入该变量,然后将其分配给枚举。 And obviously be aware that if you change your enum, you will be in trouble because the meaning of a number would change. 显然要知道,如果更改枚举,则会遇到麻烦,因为数字的含义会发生变化。 And obviously be aware that using a very short name like Low, Medium, High for an enum will get you into trouble if your program gets to any reasonable size. 显然要注意,如果程序的大小达到合理范围,则为枚举使用一个很短的名称(如Low,Medium,High)会给您带来麻烦。 Use something like eEmployeeLevel_Low instead. 请改用eEmployeeLevel_Low之类的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM