【问题标题】:Boost: unrecognised option for positional argumentBoost:位置参数无法识别的选项
【发布时间】:2015-10-26 12:07:38
【问题描述】:

我正在尝试使用 boost 1.58.0 解析命令行。我的代码非常简单,从教程中复制粘贴。看起来是这样的:

 try {
        po::options_description desc;
        desc.add_options()
                ("version,v", "Display version of application.");

        po::positional_options_description p;
        p.add("input-file", -1);

        try
        {
            po::store(po::command_line_parser(argc, argv).
                      options(desc).positional(p).run(), vm);

            if ( vm.count("version")  )
            {
                std::cout << "Program version: " << SHUF_T_VERSION << std::endl << "Boost library version: " << BOOST_LIB_VERSION << std::endl;
                return false;
            }

            po::notify(vm); // throws on error, so do after help in case
            // there are any problems
        }
        catch(po::error& e)
        {
            std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
            std::cerr << desc << std::endl;
            return false;
        }

    }
    catch(std::exception& e)
    {
        std::cerr << "Unhandled Exception: "
                  << e.what() << ", application will now exit" << std::endl;
        return false;

    }

  return true;

整个代码是here。 代码似乎是正确的。 app -v 已正确处理。但是,如果我包含任何立场争论,例如app myfile po::store() 抛出unrecognised option 'myfile'。关于为什么会发生这种情况的任何想法?

【问题讨论】:

    标签: c++ boost boost-program-options


    【解决方案1】:

    您需要添加“输入文件”作为选项:

    po::options_description desc;
    desc.add_options()
            ("version,v", "Display version of application.")
            ("input-file", po::value<std::vector<std::string> >(), "input file");
    

    来自the tutorial

    “输入文件”选项指定要处理的文件列表。一开始没关系,但是,当然,写这样的东西:

    编译器 --input-file=a.cpp

    相比有点不标准
    编译器 a.cpp

    我们稍后会解决这个问题。

    如上所述,没有选项名称的命令行标记被这个库称为“位置选项”。它们也可以处理。在用户的一点帮助下,库可以确定“a.cpp”实际上与“--input-file=a.cpp”的含义相同。这是我们需要的额外代码:

    po::positional_options_description p;
    p.add("input-file", -1);
    
    po::variables_map vm;
    po::store(po::command_line_parser(ac, av).
              options(desc).positional(p).run(), vm);
    po::notify(vm);
    

    【讨论】:

    • 如果您不想为位置参数添加长/短选项怎么办?
    猜你喜欢
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    • 2020-07-02
    相关资源
    最近更新 更多