You can't assign a string to a variable with type enum
. Enum in C is a type that consists of integral constants
. You either need to work with the pre processor or create a custom function that will set the enum cmd
the correct value by comparing argv
. This works:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CMDS 3
typedef enum { hello , hi , bye}cmd;
cmd decide_command(char *arg)
{
char *commands[] = { "hello", "hi" ,"bye" };
for (int i = 0; i < MAX_CMDS; i++)
{
if (!strcmp(commands[i],arg)) /* comparing each of the commands with argv[1] */
{
return i; /* since hello == 0 in enum cmd, the correct value will set, if found */
}
}
fprintf(stderr,"Unknown command %s",arg);
exit(EXIT_FAILURE);
}
int main(int argc,char **argv)
{
cmd command = 0;
if (argc < 2)
{
/* error handling */
}
command = decide_command(argv[1]);
/* code */
exit(EXIT_SUCCESS);
}