boost 分析命令行參數
睿豐德科技 專注RFID識別技術和條碼識別技術與管理軟件的集成項目。質量追溯系統、MES系統、金蝶與條碼系統對接、用友與條碼系統對接
[cpp] view plaincopy
- #include <boost/program_options.hpp>
- #include <iostream>
- #include <vector>
- using namespace std;
- using namespace boost::program_options;
- int main(int argc, char* argv[])
- {
- string one ; // 外部變量 存儲 參數one的值
- vector<string> mult;
- boost::program_options::options_description opts("test options");
- opts.add_options()
- ("help,h","help info")
- ("test1,t",value<string>(),"test aaa ")
- ("one,o",value<string>(&one)->default_value("one"),"test one default") // 默認值
- ("mult,m",value<vector<string> >(&mult)->multitoken(),"mult test"); //多個參數
- variables_map vm;
- try
- {
- store(parse_command_line(argc,argv,opts),vm); // 分析參數
- }
- catch(boost::program_options::error_with_no_option_name &ex)
- {
- cout<<ex.what()<<endl;
- }
- notify(vm); // 將解析的結果存儲到外部變量
- if (vm.count("help"))
- {
- cout<<opts<<endl;
- return -1;
- }
- if(vm.count("test1"))
- {
- cout<<vm["test1"].as<string>()<<endl;
- }
- cout<<one<<endl;
- cout<<mult.size()<<endl;
- getchar();
- return 0;
- }
[root@localhost test4]# g++ main.cpp -l boost_program_options
[root@localhost test4]# ./a.out -h
test options:
-h [ --help ] help info
-t [ --test1 ] arg test aaa
-o [ --one ] arg (=one) test one default
-m [ --mult ] arg mult test
[root@localhost test4]# ./a.out -m f2 f3 f4 --test1 testbbbb
testbbbb
one
3