Minimal command line argument processing

Dec 24, 2012

I recently came across an easy way to process command line arguments in C++ for throwaway programs:

vector<string> args(argv + 1, argv + argc);

This will give you a vector of strings containing the command line arguments.

A quick summary why this works. Say you run a program as

./program arg1 arg2 arg3

In main(int argc, char** argv), we will have argc = 4 and

argv = {"./program", "arg1", "arg2", "arg3"};

args is initialized using the vector constructor:

vector(InputIterator first, InputIterator last);

because you can treat pointers as iterators.

Full example:

// Example usage:
//   clang++ -std=c++11 commandline.cc -o commandline && \
//       ./commandline arg1 arg2 arg3 ...

#include <iostream>
#include <string>
#include <vector>

using std::cout;
using std::endl;
using std::string;
using std::vector;

int main(int argc, char** argv) {
  vector<string> args(argv + 1, argv + argc);

  for (const string& arg : args) {
    cout << arg << endl;
  }

  return 0;
}
←Things you should know: vtables The Power of Habit→