views:

4550

answers:

5

Duplicate of:


What is the best way of parsing command-line arguments in C++ if the program is specified to be run like this:

prog [-abc] [input [output]]

Is there a library in STL to do this?


Related:

+20  A: 

Boost.Program_options should do the trick

Good choice. Alternatively, if you can't use boost for some reason then the standard c based "getopt" function will also get the job done.
Matt H
+2  A: 

You can use GNU Getopt or one of the various C++ ports, such as getoptpp.

Matthew Flaschen
FYI, GNU getopt is GPL and getoptpp is also GPL so boost variant could be better for non open-source software.
Sorin Sbarnea
+3  A: 

I'd recommend boost::program_options if you can use the Boost lib.

There's nothing specific in STL nor in the regular C++/C runtime libs.

Marcus Lindblom
+7  A: 

The suggestions for boost::program_options and gnu getopt are good ones.

However for simple command line options I tend to use std::find

For example to read the name of a file after a "-f" command line argument

int main(char * argv[], int argc)
{
    char * filename = getCmdOption(argv, argv + argc, "-f");

    if (filename)
    {
     // Do interesting things
     // ...
    }

    return 0;
}


char* getCmdOption(char ** begin, char ** end, const std::string & option)
{
    char ** itr = std::find(begin, end, option);
    if (itr != end && ++itr != end)
    {
     return *itr;
    }
    return 0;
}

On thing to look out for with this approach you must use std::strings as the value for std::find otherwise the equality check is performed on the pointer values.

iain
A: 

Try CLPP library. It's simple and flexible library for command line parameters parsing. Header-only and cross-platform. Uses ISO C++ and Boost C++ libraries only. IMHO it is easier than Boost.Program_options.

Library: http://sourceforge.net/projects/clp-parser

26 October 2010 - new release 2.0rc. Many bugs fixed, full refactoring of the source code, documentation, examples and comments have been corrected.

Denis Shevchenko