From the user perspective, they simply add the extra arguments to the end of
the command they use to start the program, e.g. the command below would run the
executable named progx, passing parameters "123" and "Dave" to the main routine
as text strings.
./progx 123 Dave
Within the program that needs to use these arguments, we need to declare the main
routine exactly as follows:
int main(int argc, char *argv[])
Within the main routine, when the program starts, argc will automatically have been initialized with a count of the number of words in the user command, and array argv[] stores the words.
Consider the call below:
./progx 123 Dave
argc would be 3, argv[0] would contain "./progx", argv[1] would contain "123",
and argv[2] would contain "Dave"
The program below can take any number of command line arguments, and displays them back to the user:
#include <cstdio> // the parameters to main MUST be int argc and char* argv[], // do NOT change the names, the types, or the order int main(int argc, char* argv[]) { // whatever the user types on the command line to run your program // will be stored as words in argv // for instance, if they type // ./observe7x hi there 3.14 // then the contents of argv are as follows: // argv[0] contains "./observe7x" // argv[1] contains "hi" // argv[2] contains "there" // argv[3] contains "3.14" // and argv is 4 // we can print all the command line arguments the user typed in using for (int i = 0; i < argc; i++) { printf("arg %i: %s\n", i, argv[i]); } // end main return 0; } |