'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
Solution 1:[1]
Here is the right answer:
*#include <stdio.h>
int main(int argc, char**argv)// Don't worry on the arguments.
{
enum priority {
L , l, n, h, H // Todo: Priority enum Lowest =
// 0 Highest = 4
}priorityvar;
char x, option;
printf("Priority: ");
scanf(" %c", &x);
option=x;
priorityvar = option;
printf("%c", priorityvar);
return 0;
}
It was ran in Code:Blocks ver 16.1 on debian 9.13 on Xfce 4.12
Solution 2:[2]
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*/ }
or if you want letter representing the priority:
switch(option)
{
case 'L':
priorityvar = L;
break;
case 'l':
priorityvar = l;
break;
case 'n':
priorityvar = n;
break;
case 'h':
priorityvar = h;
break;
case 'H':
priorityvar = H;
break;
default:
/* handle error */
break;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeremy Caney |
| Solution 2 | 0___________ |
