Main   Classes   Namespace members   Examples   Recipes   Rationale   Related pages

Custom syntax

Some applications use a custom syntax for the command line. In this example, the gcc style of "-fbar"/"-f" is handled.

#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>

using namespace boost::program_options;

#include <iostream>
using namespace std;

/*  This custom option parse function recognize gcc-style 
    option "-fbar" / "-fno-bar".
*/
pair<string, string> reg_foo(const string& s)
{
    if (s.find("-f") == 0) {
        if (s.substr(2, 3) == "no-")
            return make_pair(s.substr(5), string("false"));
        else
            return make_pair(s.substr(2), string("true"));
    } else {
        return make_pair(string(), string());
    }    
}

int main(int ac, const char **av)
{
    try {
        options_description desc("Allowed options");
        desc.add_options()
        ("help", "", "produce a help message")
        ("foo", "true/false?", "just an option")
            .default_parameter("true")
        ;

        options_and_arguments oa = parse_command_line(ac, av, desc, 0, reg_foo);

        if (oa.count("help")) {
            cout << desc;
            cout << "\nIn addition -ffoo and -fno-foo syntax are recognized.\n";
        }
        if (oa.count("foo")) {
            cout << "foo parameter with the value of " << oa["foo"] << "\n";
        }
    }
    catch(exception& e) {
        cout << e.what() << "\n";
    }
}

Generated on 23 May 2003 with
doxygen