为什么Getopt只执行if语句?

时间:2015-02-14 17:02:54

标签: c getopt

我正在使用getopt从终端解析参数,这对我来说是一个痛苦的背面。

此c程序通过获得下限和上限来计算斐波那契序列,该命令可以给出:./run -l 0 -u 100(下限-l,上限-u./run -l 0 100。字符串“-u”(上限是一个可选参数,当给出“-u”时或者只给出上限值时,代码必须处理这两种情况)

程序将始终进入if语句,检查何时未给出-v,即使我在命令中给出了-v。

以下源代码:

int main (int argc, char **argv) {

int L_flag = 0;
int U_flag = 0;
int lower_limit;
int upper_limit;
int c;

// when no -u was given from input
if (argv[2][0] != '-'){
lower_limit = atoi (argv[2]);
upper_limit = atoi (argv[3]);
printf("lower_limit without -v: %d\n", lower_limit);
printf("upper_limit without -v: %d\n", upper_limit);
optind = 3;
}

//When -u is given
while ((c = getopt (argc, argv, "l:u")) != -1){
        switch (c){
        case 'l':
            L_flag = 1;
            lower_limit = atoi (optarg);
                        printf("here1: %d\n", lower_limit);
            break;
        case 'u':
            U_flag = 1;
            upper_limit = atoi (optarg);
                        printf("here1: %d\n", upper_limit);
                        break;
}
return 1;
}

2 个答案:

答案 0 :(得分:0)

除了检查

if (argv[3][0] != '-')

要区分这两种情况,您还应该将对getopt()的调用更改为

while ((c = getopt(argc, argv, "l:u:")) != -1) {

-u之后获取正确的参数。

答案 1 :(得分:0)

如果' -v'的含义会很好。被提及,如果代码是强制参数的特定顺序。

无论如何,举个例子:' ./ run -l 0 -u 100'

argv[0] is a pointer to the string "./run"
argv[1] is a pointer to the string "-l"
argv[2] is a pointer to the string "0"
argv[3] is a pointer to the string "-u"
argv[4] is a pointer to the string "100"
argv[5] is a NULL pointer

However, the specific string pointed to by argv[x] 
(other than argv[0])
varies depending on what the user actually input

suggest something like:

if( 1 >= argc )
{ 
    // handle error and exit
}


for(int i=1; i<argc; i++)
{

    if ( argv[i][0] == '-' )
    { // then option found
        switch( argv[i][1] )
        {
            case 'v':
                break;

            case 'l':
                i++;
                lowerLimit = atoi( argv[i] );
                break;

            case 'u':
                i++;
                upperLimit = atoi( argv[i] );
                break;

            default:
                printf( "\ninvalid parameter: %s\n", argv[i] );
                break;
        } // end switch
    }
    else
    { // else argument with no leading identifier, assume upper limit
         upperLimit = atoi( argv[i] );
    } // end if
} // end for

这不如使用getopt()那么强大,但可以完成工作