char flag = 0; // to mark which options were set
int aopt = INT_MAX; // default to INT_MAX if no args delivered
char bemerkung[100];
memset(bemerkung, '\0', 100); // string to receive via '-b'
char option;
while((option = getopt (argc, argv, "m:a:b:")) != EOF){
switch( option ){
case 'm': {
flag = flag | 1;
break;
}
case 'a': {
flag = flag | 2;
char * arg = optarg;
aopt = atoi(arg);
if(aopt == 0 && strcmp("0", arg) != 0) // if no valid optarg was entered
aopt = INT_MAX; // get back the default value
break;
}
case 'b': {
flag = flag | 4;
strcpy(bemerkung, optarg);
break;
}
default: {
fprintf(stderr, "Unknown option entered.\n");
return -1;
}
}
}
// some code here, not touching `flag`
if(flag == 1){
// deal with `-m`, no optargs
}
if(flag == 2){
// `-a aopt` called
}
if(flag == 3){
// `-m -a aopt` called
}
flag
-m
需要参数(对于
-米
./main -m -a 0
结果进入
flag = 1
而不是
flag = 3
.
我该如何为你辩护
-米
OR
正确处理
?