Accessing Parameters in main

In this example, the number of arguments is 4:
  xlC -o Lab6 program6.cpp

argv[0] is "xlC"
argv[1] is "-o"
argv[2] is "Lab6"
argv[3] is "program6.cpp"
Assume we have a C++ file named program6.cpp and we compile it under Turbo C++. The executable file will be called program.exe. Compiling under UNIX, the executable will be called a.out.
#include <iostream.h>

void main(int paramCount, char *paramList[])
{
  for (int i = 0; i < paramCount; i++)
  {
    cout << "Parameter #" << i << " is ";
    cout << paramList[i] << endl;
  }
}

Typing this at the DOS prompt:
program6 lexicon.txt input.txt output.txt 100

Causes this output from the program:
Parameter #0 is D:\DATA\PCC\CS161\PROGRAM6.EXE
Parameter #1 is lexicon.txt
Parameter #2 is input.txt
Parameter #3 is output.txt
Parameter #4 is 100
It is important to remember that each argument is represented as a string. The number 100 is not the integer 100, but it is the string "100".

Previous page
Next page

Back to Lesson 16 Index
Back to Outline