Those arguments are passed to the "main" function. Main is passed two parameters - an integer that indicates the number of command line arguments, and an array of strings (the list of arguments).
For example, if we issued the command "a.out hi mom", then argc would equal 3, argv[0] would contain "a.out", argv[1] would contain "hi", and argv[2] would contain "mom".
Here is an example of a full program that processes command line arguments. The program computes the factorial of a value. Note that argv is an array of strings. So, even though the user types in a number, main is passed a string that must be converted into an integer.
/************************************* Program to demo argv and argc Calcultate the factorial of a number *************************************/ #include <iostream> #include <stdlib.h> using namespace std; int main(int argc, char *argv[]) { int input_val; // integer version of argv[1] int output; // the factorial int i; // test for correct number of arguments if (argc < 2) { cout << "Usage: fact num\n\n"; exit(1); } // convert string to integer input_val = atoi(argv[1]); // test for not above 1 if (input_val < 2) { cout << "value too small\n"; exit (1); } // calculate the factorial output = 1; for (i=input_val; i>1; i--) output = output * i; cout << input_val << "! = " << output << endl; } |
For example,
>calc Usage error: calc int operation int >calc 2 + 2 4 >calc 15 - 5 10This program is due one week from today.