2014-10-05 73 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之類的東西。

相關問題