What's an effective way to parse command line parameters in C++?

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 num2n";
      exit(1);
   }
   int a = atoi(argv[1]);    int b = atoi(argv[2]);    int sum = a + b;
   cout << "Sum: " << sum << "n";
   return 0; }

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.


You could use an already created library for this

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


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

链接地址: http://www.djcxy.com/p/40582.html

上一篇: >在C ++中调用Method

下一篇: 在C ++中解析命令行参数的有效方法是什么?