[英]how do I use enum and argv together?
enum cmd {hello, hi, bye};
int main(int argc, char *argv[]) {
if(argc < 2)
usage(usg);
enum cmd command = argv[1];
if(command == 0) {
...
}
}
I get this error incompatible types when initializing type 'enum cmd' using type 'char *
is there different way using enum? incompatible types when initializing type 'enum cmd' using type 'char *
使用枚举有不同的方式吗?
You can't assign a string to a variable with type enum
.您不能将字符串分配给类型为
enum
的变量。 Enum in C is a type that consists of integral constants
. C 中的枚举是由
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
.您要么需要使用预处理器,要么创建一个自定义 function 通过比较
argv
将enum cmd
设置为正确的值。 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.