Possible Duplicate:
What parameter parser libraries are there for C++?
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:
You can use GNU GetOpt (LGPL) or one of the various C++ ports, such as getoptpp (GPL).
A simple example using GetOpt of what you want (prog [-ab] input) is the following:
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. You can also just detect if a single-word option has been passed in like-h
for help.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.
I hope it is okay to edit this response instead adding a new one, as this is based on the original answer. I re-wrote the functions slightly and encapsulated them in a class, so here is the code. I thought it might be practical to use it that way as well:
Yet another alternative is The Lean Mean C++ Option Parser:
http://optionparser.sourceforge.net
It is a header-only library (just a single header file, in fact) and unlike all the other suggestions it is also freestanding, i.e. it has no dependencies whatsoever. In particular there's no dependency on the STL. It does not even use exceptions or anything else that requires library support. This means it can be linked with plain C or other languages without introducing "foreign" libraries.
Like boost::program_options its API offers convenient direct access to options, i.e. you can write code like this
and
Unlike boost::program_options however this is simply using an array indexed with a (user-provided) enum. This offers the convenience of an associative container without the weight.
It's well documented and has a company-friendly license (MIT).
TLMC++OP includes a nice formatter for usage messages that can do line-wrapping and column alignment which is useful if you're localizing your program, because it ensures that the output will look good even in languages that have longer messages. It also saves you the nuisance of manually formatting your usage for 80 columns.
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.
Boost.Program_options should do the trick