2008/9/11

C++ command-line arguments

When running a C++ program in command-line mode in Unix (e.g. telnet or dtterm session), or in MSDOS mode on Windows, you can type extra arguments following the program name. These arguments are automatically passed as string parameters to the main routine.
For instant, if our program name is a.out, we may type in ./a.out -m 20 -n 30 -z 90 -haha happy from the terminal, and the string "may" would automatically be passed as a parameter to the main routine of our a.out program.
To use these parameters, we must specify in our main routine what the parameter names and types are, and the format is exactly as follows:
int main(int argc, char *argv[])
Each argument is passed as a seperate character array, so argv[1] points to the first argument text, argv[2] points to the second argument text, etc. (argv[0] gives you the name of the executable file for the program itself)
example
How to execute:
./a.out -n 30 -m 40