2017-08-22 65 views
1

以下是已使用boost::program_options的代碼。Boost ::位置選項無法使所有參數位置

#include <iostream> 
#include <vector> 

#include <boost/program_options.hpp> 

int main (int argc, char* argv[]) { 
    int n; 
    std::string mps_name; 

    boost::program_options::options_description desc("options"); 
    desc.add_options() 
     ("file", boost::program_options::value<std::string>(&mps_name)->required(), 
     "input file") 
     (",n", boost::program_options::value<int>(&n)->required(), 
     "number") 
     ("help", "this help message") 
     ; 

    boost::program_options::positional_options_description p; 
    p.add("file", 1); 
    p.add(",n", 1); 

    boost::program_options::variables_map vm; 

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

     if (vm.count("help") || argc == 1) { 
      std::cout << "usage: " << argv[0] << " [options]" << std::endl; 
      std::cout << desc; 
      return -1; 
     } 

     boost::program_options::notify(vm); 
    } 
    catch (std::exception& e) { 
     std::cout << e.what() << std::endl; 
     return -1; 
    } 

    std::cout << "command line arguments parsed" << std::endl; 

    return 0; 
} // main 

當代碼以所有參數作爲位置參數執行時。 boost拋出異常unrecognised option '5'。當代碼與./a.out earth 5

代碼執行時與命令./a.out --file earth -n 5

回答

0

的問題是執行完美的作品是positionals只長名稱對應選項的說明。這裏有一個工作版本:

boost::program_options::options_description desc("options"); 
desc.add_options() 
    ("file", boost::program_options::value<std::string>(&mps_name)->required(), "input file") 
    ("n,n", boost::program_options::value<int>(&n)->required(), "number") 
    ("help", "this help message") 
    ; 

boost::program_options::positional_options_description p; 
p.add("file", 1); 
p.add("n", 1); 

Live On Coliru

打印

./a.out ltuae 42 
command line arguments parsed: ltuae 42