zhujian

揣着梦想骑驴找马但不虐待驴
posts - 10, comments - 7, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

Boost program_options

Posted on 2011-01-13 11:17 逐渐 阅读(1823) 评论(0)  编辑 收藏 引用
boost program_options库可以帮助我们解析程序参数,支持命令行形式和配置文件形式,获得(name, value)对.下面我们以一个模拟编译器例子介绍program_options库的应用,在下一节继续介绍program_options整个库.

 1 #include <boost/program_options.hpp>
 2 
 3 #include <vector>
 4 #include <iostream>
 5 #include <string>
 6 #include <algorithm>
 7 #include <iterator>
 8 using std::copy;
 9 using std::vector;
10 using std::string;
11 using std::cout;
12 using std::endl;
13 using std::exception;
14 using std::ostream;
15 using std::ostream_iterator;
16 
17 namespace po=boost::program_options;
18 
19 // output vector.
20 template <typename T>
21 ostream& operator<<(ostream& os, const vector<T>& v)
22 {
23     copy(v.begin(), v.end(), ostream_iterator<T>(os, " "));
24     return os;
25 }
26 
27 int main(int argc, char*argv[])
28 {
29     try
30     {
31         po::options_description desc("general descriptions.");
32         desc.add_options()
33             ("help""generate help information")
34             ("input-file", po::value<vector<string> >(), "input files")
35             ("link-file,l", po::value<vector<string> >(), "link file");
36 
37         po::variables_map vm;
38         po::store(po::parse_command_line(argc, argv, desc), vm);
39         po::notify(vm);
40 
41         if(vm.count("help"))
42         {
43             cout<<desc<<endl;
44             return 1;
45         }
46 
47         if(vm.count("input-file"))
48         {
49             cout<<"Input files: "<<vm["input-file"].as<vector<string> >()
50                 <<"\n";
51         }
52 
53         if(vm.count("link-file"))
54         {
55             cout<<"Link file: "<<vm["link-file"].as<vector<string> >()
56                 <<"\n";
57         }
58     }
59     catch(exception& e)
60     {
61         cout<<e.what()<<endl;
62         return -1;
63     }
64 
65     return 0;
66 }
67 

程序第20行重载了<<运算符,用于输出vector数组.
第31行定义一个选项描述组件,然后添加允许的选项,add_options()方法返回一个特定对象,该对象重载了()运算.link-file选项指定了短名l,这样--link-file与-l一个意思.
第37行定义一个存储器组件对象vm.
第38行分析器parse_command_line将选项描述存储至vm,这里用到的分析器很简单,后面会介绍更复杂的应用.

接下来的代码就是比对vm中存放的选项了,简单吧,很好理解.下面是运行截图,编译需要添加boost program_options库,即-lboost_program_option

对于input-file选项,每次都要输出--input-file真的很麻烦,能不能用compiler main.cpp呢,当然可以.这种选项叫做positional option, 在第36行处加上如下代码:
1         po::positional_options_description p;
2         p.add("input-file"-1);
3 

修改第38行,我们要用到功能更强大的command_line_parse,改成如下:
1  po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
编译运行:看下结果吧

先到这里吧,接下来再看从文件中读选项:)



只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理