【问题标题】:Why do I always get default values when passing positional arguments?为什么我在传递位置参数时总是得到默认值?
【发布时间】:2013-05-18 19:06:47
【问题描述】:

我正在尝试熟悉 boost::program_options,但我遇到了位置参数的问题。

这是我的main 函数,我在其中设置通过命令行传递的选项。请注意poboost::program_options 的命名空间别名。

int main(int argc, char** argv)
{
    int retval = SUCCESS;
    try
    {
        // Define and parse the program options
        po::options_description desc("Options");
        desc.add_options()
          ("help", "Print help messages")
          ("mode,m", po::value<std::string>()->default_value("ECB"), "cipher mode of operation")
          ("keyfile,f", po::value<bool>(), "Use keyfile")
          ("key,k", po::value<std::string>(), "ASCII key")
          ("infile", po::value<std::string>()->default_value("plaintext.txt"), "input file")
          ("outfile", po::value<std::string>()->default_value("ciphertext.txt"), "output file");

        po::positional_options_description pargd;
        pargd.add("infile", 1);
        pargd.add("outfile", 2);

    po::variables_map vm;
    try
    {
        po::store(po::parse_command_line(argc, argv, desc), vm); // can throw

      // --help option
      if ( vm.count("help")  )
      {
        std::cout << "Basic Command Line Parameter App" << std::endl
                  << desc << std::endl;
        return SUCCESS;
      }

        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 ERROR_IN_COMMAND_LINE;
    }

    ///application code here
    retval = application(vm);

    }
    catch(std::exception& e)
    {
        std::cerr << "Unhandled Exception reached the top of main: "
                  << e.what() << ", application will now exit" << std::endl;
        return ERROR_UNHANDLED_EXCEPTION;
    }

    return retval;
} // main

当我尝试使用cout &lt;&lt; wm["infile"].as&lt;std::string&gt;(); 打印vm(variable_map)的位置参数时,我总是得到“infile”参数的默认值。

我将可执行文件称为./a.out in.file out.file 进行测试。

我做错了什么?

【问题讨论】:

  • 显示为你怎么称呼它,你用什么命令行...
  • @K-ballo,好点,对不起!我称它为./a.out in.file out.file

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


【解决方案1】:

我想通了!

po::store(po::parse_command_line(argc, argv, desc), vm);

应该是……

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

虽然我不确定我是否理解为什么...

【讨论】:

  • 在第一种情况下,解析器既没有直接也没有间接处理位置信息 (pargd)。因此,对于./a.out in.file out.file,Boost.ProgramOptions 会忽略in.fileout.file;如果它们看起来像一个以连字符开头的选项,它将失败。第二种情况有效,因为解析器现在可以使用位置信息。
  • @TannerSansbury,我明白了。完全有道理。谢谢!
猜你喜欢
  • 2022-11-30
  • 2021-07-03
  • 1970-01-01
  • 1970-01-01
  • 2014-12-31
  • 1970-01-01
  • 2012-05-22
  • 1970-01-01
  • 2014-04-09
相关资源
最近更新 更多