How easily and quickly can you specify arguments for your program in C++

Problematic

All programs don’t have a graphical user interface, and even those whom have one can also be called using a shell/bash/batch command in the Terminal of you choice. When you want to use the command line to run a program, most of the time, you can also pass some arguments to the program, and have it do some specific task it is programmed for.

Solution

We are going to look at two ways to do such thing in C++ : the “old” native solution and a modern one

Native solution: argc and argv

This is the old and native solution to solve this problem in C++. I say it is an old solution because it is inherited from C language which starts to be a very old language in the history of programming languages.

int main(int argc, char* argv[]) {
for(auto i=0; i< argc; ++i) {
std::cout << argv[i] << std::endl;
}
return EXIT_SUCCESS;
}

Modern solution: Argh!

If you use some more modern technologies in your C++ development environment, then you should at least try this solution to process your command line. Argh! is a header only library, easy to include, either by copy-paste, or via conan into your own build system or into a CMake project. So no problem with that (you can also look at the details on the documentation).

#include <iostream>
#include "argh.h"
int main(int, char* argv[]) {
argh::parser cmdl(argv);
if (cmdl[{ "-v", "--verbose" }])
std::cout << "Verbose, I am.\n";
return EXIT_SUCCESS;
}
float scale_factor;
cmdl({"-s", "--scale"}, 1.0f) >> scale_factor; // Use 1.0f as default value

Interesting links

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store