In a typical C++ application, the main() function receives an array and a count as command line parameters — parameters provided as part of the command to execute that application at the command line. However, to beginning programmers, the parameters can look intimidating. But they’re not:
Think of the two parameters as an array of strings and a size of the array. However, each string in this array of strings is actually a character array. In the old days of C, and earlier breeds of C++, no string class was available. Thus strings were always character arrays, usually denoted as char *MyString. (Remember, an array and a pointer can be used interchangeably for the most part).
Thus you could take this thing and turn it into an array — either by throwing brackets at the end, as in char *MyString[ ], or by making use of the fact that an array is a pointer and adding a second pointer symbol, as in char **MyString. The following code from the CommandLineParams example shows how you can get the command-line parameters:
#include <iostream> using namespace std; int main(int argc, char *argv[]) { int loop; for (loop = 0; loop < argc; loop++) { cout << argv[loop] << endl; } return 0; }
When you compile this application, name the executable CommandLineParams, and then run it from the command prompt, using the following command:
CommandLineParams abc def "abc 123"
You see the following output. (Note that the application name comes in as the first parameter and the quoted items come in as a single parameter.)
CommandLineParams abc def abc 123
You can also specify command-line arguments using the IDE for debugging purposes when working with the Code::Blocks compiler. Choose Project→Set Program’s Arguments. Code::Blocks displays the Select Target dialog box, where you choose a target in the first field and type the arguments in the Program Arguments field. Click OK and then click Run. CommandLineParams displays the command-line arguments in the command window as it did when you typed the command at the command prompt.