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:
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:
You can use GNU Getopt or one of the various C++ ports, such as getoptpp.
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.
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.
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.