boost :: program_options中带和不带参数的参数

问题描述 投票:7回答:1

我写了一个小应用程序,它使用boost :: program_options进行命令行解析。如果参数存在,我想有一些设置值的选项,如果给出参数但是没有参数,则交替打印当前值。所以“设置模式”看起来像:

dc-ctl --brightness 15

和“获取模式”将是:

dc-ctl --brightness
brightness=15

问题是,我不知道如何处理第二种情况而不捕获此异常:

error: required parameter is missing in 'brightness'

是否有一种简单的方法可以避免它抛出该错误?一旦解析了参数,就会发生这种情况。

c++ command-line-arguments boost-program-options
1个回答
4
投票

我得到了How to accept empty value in boost::program_options的部分解决方案,建议对那些可能存在或不存在参数的参数使用implicit_value方法。所以我初始化“brightness”参数的调用如下所示:

 ("brightness,b", po::value<string>()->implicit_value(""),

然后我迭代变量映射,对于任何一个字符串的参数,我检查它是否为空,如果是,我打印当前值。该代码如下所示:

    // check if we're just printing a feature's current value
    bool gotFeature = false;
    for (po::variables_map::iterator iter = vm.begin(); iter != vm.end(); ++iter)
    {
        /// parameter has been given with no value
        if (iter->second.value().type() == typeid(string))
            if (iter->second.as<string>().empty())
            {
                gotFeature = true;
                printFeatureValue(iter->first, camera);
            }
    }

    // this is all we're supposed to do, time to exit
    if (gotFeature)
    {
        cleanup(dc1394, camera, cameras);
        return 0;
    }

更新:这改变了上述语法,当使用隐式值时,现在参数在给定时必须是以下形式:

./dc-ctl -b500

代替

./dc-ctl -b 500

希望这对其他人有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.