2017-08-02 76 views
-2

我試圖用boost來解析命令行參數。這裏是我的代碼(我只包括我需要幫助的部分):用boost.program_options分析命令行參數 - C++

#include <iostream> 
#include <iterator> 
#include <boost/program_options.hpp> 

using std::cerr; 
using std::cout; 
using std::endl; 
namespace po = boost::program_options; 

try { 

    po::options_description desc("Allowed options"); 
    desc.add_options() 
     ("help", "produce help message") 
     ("compression", po::value<double>(), "set compression level"); 

    po::variables_map vm; 
    po::store(po::parse_command_line(ac, av, desc), vm); 
    po::notify(vm); 

    if (vm.count("help")) { 
     cout << desc << "\n"; 
     return 0; 
     } 

    if (vm.count("compression")) { 
     cout << "Compression level was set to " 
      << vm["compression"].as<double>() << ".\n"; 
     } else { 
      cout << "Compression level was not set.\n"; 
      } 
     } 
    catch(exception& e) { 
     cerr << "error: " << e.what() << "\n"; 
     return 1; 
    } 
    catch(...) { 
     cerr << "Exception of unknown type!\n"; 
    } 

我有我的主要功能設置爲:

main(int argc, char const *argv[]) 

但是,我下面https://github.com/boostorg/program_options/blob/develop/example/first.cpp包含這些參數的代碼:

int main(int ac, char* av[]) 

當我comile,它吐出了這一點,我完全失去了:

Terminal return

+0

請不要發佈文字的圖像。相反,將文本*作爲文本*複製粘貼到問題中。 –

+0

要麼只是改變你的主要功能爲「int main(int ac,char * av [])」或找到每個「ac」出現的地方並將其更改爲「argc」,同樣將「av」更改爲「argv」,您應該很好去 – systemcpro

+0

至於參數的名稱,它們並不重要。 'argc'和'argv'只是兩個常用的名字,縮寫'ac'和'av'也是。如果你願意,你可以將它們命名爲「foo」和「bar」。 –

回答

1

你也忘了,包括例外 - 這裏是你的代碼工作..

#include <iostream> 
#include <iterator> 
#include <boost/program_options.hpp> 
#include <exception> 

using std::cerr; 
using std::cout; 
using std::endl; 
using std::exception; 
namespace po = boost::program_options; 

int main(int ac, char** av){ 

try { 

    po::options_description desc("Allowed options"); 
    desc.add_options() 
     ("help", "produce help message") 
     ("compression", po::value<double>(), "set compression level"); 

    po::variables_map vm; 
    po::store(po::parse_command_line(ac, av, desc), vm); 
    po::notify(vm); 

    if (vm.count("help")) { 
     cout << desc << "\n"; 
     return 0; 
     } 

    if (vm.count("compression")) { 
     cout << "Compression level was set to " 
      << vm["compression"].as<double>() << ".\n"; 
     } else { 
      cout << "Compression level was not set.\n"; 
      } 
     } 
    catch(exception& e) { 
     cerr << "error: " << e.what() << "\n"; 
     return 1; 
    } 
    catch(...) { 
     cerr << "Exception of unknown type!\n"; 
    return 1; 
    } 
return 0; 
} 

g++ -std=c++11 cmd.cpp -l boost_program_options 

編譯這一點,你應該罰款

其實你可以離開如果你願意,可以輸出「std = C++ 11」。我已經嘗試過,兩者都OK