Home

Arrays and Command-Line Parameters in C++

|
Updated:  
2016-03-26 08:29:41
|
C++ For Dummies
Explore Book
Buy On Amazon

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.

About This Article

This article is from the book: 

About the book author:

John Paul Mueller is a freelance author and technical editor. He has writing in his blood, having produced 100 books and more than 600 articles to date. The topics range from networking to home security and from database management to heads-down programming. John has provided technical services to both Data Based Advisor and Coast Compute magazines.

Jeff Cogswell has been an application developer and trainer for 18 years, working with clients from startups to Fortune 500 companies. He has developed courses on C++ and other technologies.