Taking Command Line Arguments

nanodano 0 Tallied Votes 182 Views Share

This snippet shows how to use command line arguments as variables in your program. A command line argument is extra information you give a program at runtime, by typing the information after the program name like so:

Linux might look like this:
user$: ./myprogram argument1 argument2

A windows command prompt would look similar to this:
C:\>myprogram arg1 arg2 arg3

It is pretty straightforward, int argc is the numbers of arguments. 1 is the minimum, which is the text used to invoke the program. char *argv[] is a pointer to a character array. argv[0] is the first element, which is the program name.

#include <iostream>

using namespace std;

int main(int argc, char *argv[]) {
  int i;
  cout << "The number of command line arguments is (argc): " << argc << '.' << endl;
  cout << "The first argument is the program(argv[0] or *argv): " << *argv << endl;
 
if (argc > 0) {
  for (i = 0; i < argc; i++)
    cout << "argv[" << i << "]: " << argv[i] << endl;
}

cout << endl;
return 0;
}