2013-05-18 50 views
3

我想讓自己熟悉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 << wm["infile"].as<std::string>();打印vm(在variable_map)的位置的說法,我總是爲「INFILE」參數的默認值。

我打電話給可執行文件作爲./a.out in.file out.file來測試。

我在做什麼錯?

+0

顯示爲你怎麼稱呼它,是什麼命令行你用... –

+0

@ K-ballo,好點,對不起!我將它稱爲'./a.out in.file out.file' – blz

回答

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);

雖然我不知道我理解爲什麼 ...

+1

在第一種情況下,解析器既沒有直接位置信息也沒有間接位置信息處理('pargd')。因此,使用'./a.out in.file out.file',Boost.ProgramOptions忽略'in.file'和'out.file';如果他們看起來像是一個選項開頭的連字符,它會失敗。第二種情況是可行的,因爲解析器現在具有要使用的位置信息。 –

+0

@TannerSansbury,我明白了。非常有意義。謝謝! – blz

相關問題