6.6.  Processing Command-Line Arguments

[ fromfile: argumentlist.xml id: cmdlineargs ]

Usage:
   a.out [-v] [-t] inputfile.ext [additional files]
     If -v is present then verbose  = true;
     If -t is present then testmode = true;

Example 6.25. src/derivation/argumentlist/argproc.cpp

[ . . . . ]
#include <cstring>

bool test = false;
bool verbose = false;

void processFile(char* filename) {
[ . . . . ]
}

/*
  @param argc - the number of arguments
  @param argv - an array of argument strings
*/
int main (int argc, char* argv[]) {
  // recall that argv[0] holds the name of the executable.
  for (int i=1; i < argc; ++i) { 1

     if (strcmp(argv[i], "-v")==0) {
        verbose = true;
     }
     if (strcmp(argv[i], "-t") ==0) {
        test = true;
     }
  }
  for (int i=1; i < argc; ++i) { 2
     if (argv[i][0] != '-') 
        processFile(argv[i]);
  }
}
[ . . . . ]

1

First process the switches.

2

Make a second pass to operate on the non-switched arguments.