使用getopt解析c ++中的程序参数 [英] Using getopt to parse program arguments in c++

查看:287
本文介绍了使用getopt解析c ++中的程序参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,它接受各种命令行参数。为了简化起见,我们将说明它需要3个标志:

I have a program which takes various command line arguments. For the sake of simplification, we will say it takes 3 flags:

-a, -b, and -c

并使用以下代码解析我的参数

and use the following code to parse my arguments

    int c;
    while((c =  getopt(argc, argv, ":a:b:c")) != EOF)
    {
        switch (c)
        {
             case 'a':
                 cout << optarg << endl;
                 break;
             case 'b':
                 cout << optarg << endl;
                 break;
             case ':':
                 cerr << "Missing option." << endl;
                 exit(1);
                 break;
        }
    }

注意:a,

但是如果我调用我的程序,我遇到一个问题:

But I run into an issue if I invoke my program say with


./myprog -a -b parameterForB

./myprog -a -b parameterForB

其中我忘记了parameterForA,parameterForA(由optarg表示)

where I forgot parameterForA, the parameterForA (represented by optarg) is returned as


-b

-b

没有参数和optind设置为argv中的parameterForB的索引

and parameterForB is considered an option with no parameter and optind is set to the index of parameterForB in argv

在这种情况下,期望的行为是:在没有为-a找到参数之后返回':' ,和缺少选项。打印为标准错误。但是,只有在-a是传递给程序的最后一个参数的情况下才会发生。

The desired behavior in this situation would be that ':' is returned after no argument is found for -a, and "Missing option." is printed to standard error. However, that only occurs in the event that -a is the last parameter passed into the program.

我想问题是:有一种方法可以使getopt假设没有选项以 - 开头?

I guess the question is: is there a way to make getopt() assume that no options will begin with '-'?

推荐答案

请参阅 getopt 的.org / onlinepubs / 000095399 / functions / getopt.html> POSIX标准定义。它表示

See the POSIX standard definition for getopt. It says that


如果[getopt]检测到缺少
选项参数,它将返回
结构如果optstring的第一个
字符是冒号,或
a问号字符('?')
,则字符(':')。

If it [getopt] detects a missing option-argument, it shall return the colon character ( ':' ) if the first character of optstring was a colon, or a question-mark character ( '?' ) otherwise.

对于该检测,




  1. 指向的字符串中的最后一个字符,argv的元素,然后optarg应该
    包含argv的下一个元素,
    optind将增加2.如果
    optind的结果值是
    大于argc,这表示
    缺少选项参数,而getopt()
    将返回错误指示。

  2. 否则,optarg应指向argv元素中的选项
    字符后面的字符串,并且
    optind将增加1.


看起来像 getopt 被定义为不做你想要的,所以你必须自己实现检查。幸运的是,您可以通过检查 * optarg 并自己更改 optind 来实现。

It looks like getopt is defined not to do what you want, so you have to implement the check yourself. Fortunately, you can do that by inspecting *optarg and changing optind yourself.

int c, prev_ind;
while(prev_ind = optind, (c =  getopt(argc, argv, ":a:b:c")) != EOF)
{
    if ( optind == prev_ind + 2 && *optarg == '-' ) {
        c = ':';
        -- optind;
    }
    switch ( …

这篇关于使用getopt解析c ++中的程序参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆