mohammadsdtmnd
mohammadsdtmnd

Reputation: 19

Initialize enum by string in c (keil v5)uvision

I'm using these code to receive string from uart then matching them with this enum then putting them on switch-case.

char temp[3],rx_buf[100];
enum form {
GGA = 1,
GSA
};
enum form gnssform ;

sprintf(temp,"%c%c%c",rx_buf[3],rx_buf[4],rx_buf[5]);
gnssform=temp;

I can't understand that we can directly use something like EXAMPLE:

gnssform=GSA;

and there is no error ,but this:

gnssform=temp;

not compiling .and please tell me the possible way to do this???,because of this EXAMPLE I believe that it must be possible. the error is :

a value of type "char *" cannot be assigned to an entity of type "enum form"

please do not tell me to use if-else because I hate that.

Finally I used

if(rx_buf[3]=='G'&&rx_buf[4]=='G'&&rx_buf[5]=='A')gnssform=GGA; 
else if(rx_buf[3]=='G'&&rx_buf[4]=='S'&&rx_buf[5]=='A')gnssform=GSA;

Upvotes: 0

Views: 458

Answers (2)

Twinkle
Twinkle

Reputation: 524

There's no built-in solution. Easiest way is with an array of char* where the enum's int value indexes to a string containing the descriptive name of that enum.

enum FRUIT_ENUM {
    apple, orange, grape, banana,
};

static const char *FRUIT_STRING[] = {
    "apple", "orange", "grape", "banana",
};

Then you can do something like below in a loop.

if (!strcmp(FRUIT_STRING[n],temp)) 
gnssform=n;

Upvotes: 1

Russ Schultz
Russ Schultz

Reputation: 2689

GSA is a constant value of enum form.

temp is a char pointer to the three letters 'GSA'.

They are not the same thing, and you cannot directly assign them.

Upvotes: 0

Related Questions