使用Boost program_options控制程序输入

简介

很多人使用界面来输入数据,本文的程序介绍如何使用Boost的program_options控制输入。
程序中使用了:
1. 短选项
2. 可以指定多个参数的选项

程序

#include <iostream>
#include <vector>
#include <string>
using namespace std;

// boost header files
#include <boost/program_options.hpp>
namespace boostpo = boost::program_options;
class Options
{
public:
    Options(int &argc, char** &argv){
        boostpo::options_description opts = boostpo::options_description("Allowed options");
        opts.add_options()
            ("help,h"         , "produce help message")
            ("int_opt,i"      , boostpo::value<int>()->default_value(0)        , "int option")
            ("string_opt,s"   , boostpo::value<std::string>()                  , "string option")
            ("float_opt,f"    , boostpo::value<float>()                        , "float option")
            ("multi_doubles,m", boostpo::value<vector<double> >()->multitoken(), "multiple doubles")
            ;
        boostpo::variables_map vm;
        try{
            boostpo::store(boostpo::parse_command_line(argc, argv, opts), vm);
        }
        catch (boost::exception &e){
            cerr << "wrong options" << endl;
            cout << opts << endl;
            exit(EXIT_FAILURE);
        }

        int_opt = vm["int_opt"].as<int>();

        if (vm.count("string_opt")){
            string_opt = vm["string_opt"].as<string>();
        }
        else{
            cout << opts << endl;
            cerr << "input string option please." << endl;
            exit(EXIT_FAILURE);
        }

        if (vm.count("float_opt")){
            float_opt = vm["float_opt"].as<float>();
        }
        else{
            cout << opts << endl;
            cerr << "input float option please." << endl;
            exit(EXIT_FAILURE);
        }

        if (vm.count("multi_doubles")){
            doubles_opt = vm["multi_doubles"].as<vector<double> >();
        }
        else{
            cout << opts << endl;
            cerr << "input multi_doubles option please." << endl;
            exit(EXIT_FAILURE);
        }
    }
public:
    int int_opt;
    float float_opt;
    std::string string_opt;
    vector<double> doubles_opt;
};

int main(int argc, char **argv){
    Options ops(argc, argv);
    cout << "int option : " << ops.int_opt << endl;
    cout << "string option : " << ops.string_opt << endl;
    cout << "float option : " << ops.float_opt << endl;
    cout << "multiple doubles : ";
    for (size_t t = 0; t < ops.doubles_opt.size(); t++){
        cout << ops.doubles_opt[t] << " ";
    }
    return EXIT_SUCCESS;
}

实验

> demo.exe  -i 12 -s hello -f 11 -m 12.4 23.4
int    option    : 12
string option    : hello
float  option    : 11
multiple doubles : 12.4 23.4

你可能感兴趣的:(boost,options)