Main   Classes   Namespace members   Examples   Recipes   Rationale   Related pages

Variables map

In this example, the parameter function is used to enable validation of options (i.e. checking that they are of correct type). The option values are also stored in program variables.

/* Demonstates validation of parameters and automatic assignment
   to program variables.
 */

#include <boost/program_options.hpp>
namespace po = boost::program_options;

#include <iostream>
#include <iterator>
using namespace std;

int main(int ac, const char* av[])
{
    using po::parameter;
    try {
        bool verbose(false);
        int magic(23);
        string word;
        vector<int> v;
        vector<string> sv;

        po::options_description desc("Allowed options");
        desc.add_options()
            ("help", "", "produce help message")
            // Here, we specify that boolean parameter is required by this
            // option, and its value should be assigned to the variable
            // 'verbose'
            ("verbose", parameter("yes/no", &verbose), "verbose output")
            ("magic", parameter("value", &magic), "magic value for the program")
            ("word", parameter("whatever", &word), "internal parameter")
            // The '+' symbol in parameter name allows the 'numbers' option 
        // to take several parameters, like 
        // --numbers 1 2 3 4
            ("numbers", parameter("list+", &v), "a list of numbers")
            // Only one value can be specified per occurence of "-I", but
            // values from all occurences will be stored in one vector.
            ("path,I", parameter("list", &sv), "some path")
            ;

        po::options_and_arguments opts = po::parse_command_line(ac, av, desc);
        po::variables_map vm;
        po::store(opts, vm, desc);

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

        cout << "Verbose set to " << verbose << "\n";
        cout << "Magic value is " << magic << "\n";
        cout << "Word is " << word << "\n";
        cout << "Numbers are ";
        copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
        cout << "\n";
        cout << "Pathes are ";
        for (size_t i = 0; i < sv.size(); ++i)
        cout << '"' << sv[i] << "\" ";        
        cout << "\n";
        cout << "Arguments are:\n   ";
        copy(opts.arguments().begin(), opts.arguments().end(),
             ostream_iterator<string>(cout, "\n   "));
        cout << "\n";


    }
    catch(exception& e) {
        cerr << "error: " << e.what() << "\n";
        return 1;
    }
    catch(...) {
        cerr << "Exception of unknown type!\n";
    }

    return 0;
}

Generated on 23 May 2003 with
doxygen