Question

I'm trying to familiarize myself with boost::program_options, and I'm running into a problem with positional arguments.

Here's my main function, where I set options passed through the command line. Please note that po is a namespace alias for boost::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

When I try to print a positional argument of vm (the variable_map) with cout << wm["infile"].as<std::string>();, I always get the default value for the "infile" parameter.

I'm calling the executable as ./a.out in.file out.file to test.

What am I doing wrong?

Était-ce utile?

La solution

I figured it out!

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

should be...

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

Although I'm not sure I understand why yet...

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top