2014-10-05 2 views
0

지금 enums 및 structs를 배우고 있으며 해결할 수없는 경우가 있습니다. 기본 구조체가 있고 직원을 정의하면 다음을 수행 할 수 있습니다.C에서 구조체 내의 열거 형에 정수 값 할당?

저는 직원을 첫 번째 항목에 추가했지만 사용자가 정수를 입력 한 다음 그 정수를 가질 수있는 방법은 무엇입니까? 구조체 내에 중첩 된 enum을 사용하여 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와 같은 것을 사용하십시오.

관련 문제