2014-10-05 72 views
0

我现在正在学习枚举和结构,并有一个我无法解决的问题。如果我有一个基本的结构并定义一个员工,我看到我可以执行以下操作。将整数值赋给C中一个struct中的枚举?

我已将员工添加到第一个项目,但是如何让用户输入一个整数然后让该整数为使用嵌套在结构中的枚举分配给Low,Medium或High?谢谢!

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 

回答

0

它可能会关闭,但你可以做这样的事情:

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 
0

这只是不能工作。 scanf需要知道它以字节读取的项目大小。但是,C没有为枚举定义这个大小。

创建一个类型为int的临时变量scanf到该变量中,然后将其分配给枚举。显而易见,如果你改变你的枚举,你会遇到麻烦,因为一个数字的含义会改变。显然,请注意,如果您的程序达到任何合理的大小,对于枚举使用非常短的名称(如Low,Medium,High)会使您陷入困境。改用eEmployeeLevel_Low之类的东西。

相关问题