Command Line Arguments Command Line Arguments Cmd.Line Args
What & Why?
- space-separated strings behind program call
- used to send information to a program when it starts
- especially useful for automation/scripting
$ ls
$ rm *.txt
$ find -name *.jpg
$ g++ -o out xy.cpp
main.cpp
#include <iostream>
int main (int const argc, char const*const* argv) {
for (int i = 0; i < argc; ++i) {
std::cout << argv[i] << '\n';
}
}
$ g++ -o exe main.cpp
$ ./exe 12 abc -z 3
./exe
12
abc
-z
3
- names
andargc
are only a conventionargv - each element of
argvis a C-string: a C-array of char argvitself is a C-array of C-stringsargv[0]contains the program call (platform dependent)
Conversion to std::string, int, …
Argument Conversion
Conversion
#include <iostream>
int main (int const argc, char const*const* argv) {
if (argc < 3) {
std::cerr << "Usage:\\n " << argv[0] << " <word> <times>\\n";
return EXIT_FAILURE;
}
auto word = std::string(argv[1]);
int times = atoi(argv[2]);
for (int i = 0; i < times; ++i) {
std::cout << word << ' ';
}
std::cout << '\n';
}
$ ./say
Usage: ./say <word> <times>
$ ./say ho! 3
ho! ho! ho!
execute without args
too few args ⇒ usage message
execute with args
program output
String → Number Conversion Functions String Conversions String Conversion
#include <cstdlib> (C-strings)
int atoi (char const*);
long atoll (char const*);
double atof (char const*);
#include <string> C++11
int stoi (std::string const&);
long stol (std::string const&);
float stof (std::string const&);
double stod (std::string const&);
Command Line Argument Parsing Libraries Args Parsing Libraries Libraries
| Library | CLI formats |
generates usage |
handles errors |
opinions |
|---|---|---|---|---|
| Argument Aggregator | fixed |
| ||
| Argh! | arbitrary |
| ||
| argparse | fixed |
| ||
| Args | flexible |
| ||
| Argtable | fixed |
| ||
| Boost Program Options | flexible |
| ||
| CLI11 | fixed |
| ||
| CLIPP | arbitrary |
| ||
| cxxopts | fixed |
| ||
| DocOpt | fixed |
| ||
| getopt | fixed |
| ||
| getopt_long | fixed |
| ||
| GFlags | fixed |
| ||
| TCLAP | flexible |
| ||
| The Lean Mean C++ Option Parser | fixed |
|