views:

102

answers:

4

Is there a really effective way of dealing with command line parameters in C++?

What I'm doing below feels completely amateurish, and I can't imagine this is how command line parameters are really handled (atoi, hard-coded argc checks) in professional software.

// Command line usage: sum num1 num2

int main(int argc, char *argv[])
{
   if (argc < 3)
   {
      cout << "Usage: " << argv[0] << " num1 num2\n";
      exit(1);
   }
   int a = atoi(argv[1]);    int b = atoi(argv[2]);    int sum = a + b;
   cout << "Sum: " << sum << "\n";
   return 0; }
+7  A: 

You probably want to use an external library for that. There are many to chose from.

Boost has a very feature-rich (as usual) library Boost Program Options.

My personal favorite for the last few years has been TCLAP -- purely templated, hence no library or linking, automated '--help' generation and other goodies. See the simplest example from the docs.

Dirk Eddelbuettel
+1, didn't know about tclap and it manages to be lightweight and yet feels complete, I'm definitely going to delve deeper.
Matthieu M.
+3  A: 

You could use an already created library for this

http://www.boost.org/doc/libs/1_44_0/doc/html/program_options.html

David
+1  A: 

if this is linux/unix then the standard one to use is gnu getopt

http://www.gnu.org/s/libc/manual/html_node/Getopt.html

pm100
Not really as the question was about C++ and Getopt is just plain C. There used to be a C++ variant of it but for some reason it was withdrawn.
Dirk Eddelbuettel
it works fine in c++ tho; its what we use in all our c++ code.
pm100
Well yes but you can do *much* better with e.g. TCLAP. I add or remove one line with new option definition and I do not need to edit code in other place --> not so true with old school getopt.
Dirk Eddelbuettel
A: 

I would recommend always using boost lexical_cast<> in place of junk like atoi, atof, etc.

http://www.boost.org/doc/libs/release/libs/conversion/lexical_cast.htm

Other than that your code okay for simple stuff.

Inverse