Command Line Arguments in C++

If you wish to implement command line arguments in your C++ program, the C++ language has an inbuilt function which looks like this

int main(int argc, char *argv[])

The first keyword argc is the number of arguments which are passed into the program from the command line. Argc will always be at least 1 because the first argument is always the name of the program. Each command line argument which is provided, will make argc to increase by one.

The second keyword argv is where the actual arguments are stored. You can use each argv element just like a string or as a two dimensional array. The use of argv may be confusing at first but they are really just an array of C style strings.

Have a look at this example code which has implemented command line arguments. Copy and paste it into Visual Studio and play around with entering command line arguments to see what the program does.

#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
 // The default command line
 if(argc == 1)
 {
 cout << "This is testing out command line arguments\n";
 }

 if (argc == 2) 
 { 
 if(argv[1][0] == 'P')
 {
 cout << "The P Command has been entered in\n";
 }

 else if(argv[1][0] == 'A')
 {
 cout << "The A command has been entered in\n";
 }
 else if(argv[1][0] == 'L')
 {
 cout << "The L command has been entered in\n";
 }
 else
 // If none of the commands are P, A or L
 cout << "None of the commands are P, A or L\n";
 }

 return 0;
}

Now you may be asking, how can input the commands I have implemented in this program, as every time you run the program, it shows the first default argument “This is testing out command line arguments”. To input command line arguments the program, follow these steps in visual studio.

1. Right click on the second line in solution explorer in visual studio and choose properties.

cla step 1

2. Click on Configuration Properties and choose Debugging

cla step 2

3. In the second option, “Command Arguments” is now where we can enter in our command line arguments.

cla step 3

4. Enter in the letter which you want the program to execute. Once you have entered in your command line arguments, click ok.

5. Close the window and run the program with Control + F5 or start without debugging.

6. Now the program is running and executing command line arguments.

cla step 4

Share this post