简体   繁体   中英

input a character into an enum variable using scanf in c

Hi guys i need to write an Program for univerity that organises a queue using an enum but im having a lot of Problems with the enum.

int main() {

enum priority {
    L , l, n, h, H      //Todo: Priority enum Lowest = 0 Highest = 4
};

char option = 'X';
printf("Priority: ");
scanf(" %c", &option);
enum priority priorityvar = option;
printf("%d", priorityvar);

The Problem is that when i'm scanning the char that the variable priorityvar is always set to the literal charcater and there isnt being recognized by the enum, and i cant read it directly into the variable because the compiler gives me warnings saying i cannot adress a variable of type enum with a %d or %c. Anybody have any idea how to solve this? I feel like this could have been solved easier without an enum but i have to use an enum to solve the task for uni

you need to convert char representing the digit to its integer value.

enum priority priorityvar;
if(isdigit((unsigned char)option && option >= '0' && option < '5') priorityvar = option - '0';
else { /* wrong input - handle error*/ }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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