【boost学习笔记】命令行解析库(program_options)

来源:互联网 发布:java进阶路线 书籍 编辑:程序博客网 时间:2024/05/16 01:01

代码:

// Copyright Vladimir Prus 2002-2004.// Distributed under the Boost Software License, Version 1.0.// (See accompanying file LICENSE_1_0.txt// or copy at http://www.boost.org/LICENSE_1_0.txt)/* The simplest usage of the library. */#include <boost/program_options.hpp>namespace po = boost::program_options;#include <iostream>#include <iterator>using namespace std;int main(int ac, char* av[]){    try {        po::options_description desc("Allowed options");        desc.add_options()            ("help,h", "produce help message")            ("compression", po::value<double>(), "set compression level")("include-path,I", po::value<std::string>(), "set path")("debugflag,D", po::value<bool>(), "set file")        ;        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";        }if (vm.count("include-path")) {cout << "include-path are :  " << vm["include-path"].as<std::string>() << ".\n";} else {cout << "include-path  was not set.\n";}if (vm.count("debugflag")) {cout << "debugflag are : " << vm["debugflag"].as<bool>() << ".\n";} else {cout << "debugflag was not set.\n";}    }    catch(exception& e) {        cerr << "error: " << e.what() << "\n";        return 1;    }    catch(...) {        cerr << "Exception of unknown type!\n";    }    return 0;}

上面程序加上如下参数运行:

testDemo --help --compression 12 -I ssssss -D true


结果:

Allowed options:
  -h [ --help ]             produce help message
  --compression arg         set compression level
  -I [ --include-path ] arg set path
  -D [ --debugflag ] arg    set file


Compression level was set to 12.
include-path are :  ssssss.
debugflag are : 1.







0 0
原创粉丝点击