(C++) argv

January 7, 2018 · View on GitHub

argv holds the first index of an array of strings, where argc holds the size of argv. With argc and argv you can access the arguments main is called with from (by the operating system).

One of the two standard forms of main is [1]:

int main(int argc, char * argv[]) {}

argv contains the filename of the program itself at index zero and then the parameters the user gave when starting the executable.

Example: show all command-line arguments

This example shows all command-line arguments:

#include <iostream>

int main(int argc, char* argv[])
{
  for(int i=0; i!=argc; ++i)
  {
    std::cout << i << " : " << argv[i] << '\n';
  }
}

If you start the program from the command-line as such:

./my_program_name Hello world

Your output will be similar to:

0 : /home/richelbilderbeek/my_program_name
1 : Hello
2 : world

The first argument, argv[0] is always the path to the program.

Example: Convert argv to std::vector<std::string>

#include <cassert>
#include <string>
#include <vector>

int main(int argc, char* argv[])
{
  const std::vector<std::string> args(argv, argv + argc);
  assert(argc == static_cast<int>(args.size());
  assert(argv[0] == args[0]);
}

To skip argv[0], use:

int main(int argc, char* argv[])
{
  const std::vector<std::string> args(argv + 1, argv + argc);
  // ...
}

 

References

  • [1] C++. International Standard. ISO/IEC 14882. Second edition. Paragraph 3.6.1.2