Create a console C++ application that takes command-line arguments
To create a console C++ application that accepts command line arguments we can make use of the main() function of our application.
All C++ programs must have a main() function. The main
function is where your source code begins execution. This function is not declared because it’s built into the language., but if it would, it will be in the form:
int main();
int main(int argc, char *argv[]);
Command Line Arguments
As described in the official documentation the argument definitions are as follows:
argc
«An integer that contains the count of arguments that follow in argv. The argc parameter is always greater than or equal to 1.» Therefore, if you pass 3 arguments, the argc would be four, since argc =1 is the name of the application.
argv
«An array of null-terminated strings representing command-line arguments entered by the user of the program. By convention, argv[0]
is the command with which the program is invoked. argv[1]
is the first command-line argument. The last argument from the command line is argv[argc - 1]
, and argv[argc]
is always NULL.»
There are more arguments defined in the documentation but we will focus in these two.
Processing the command line arguments
Here is an example of how to process and display the command line arguments passed to the program. In this example, the arguments are being printed into the console.
#include <iostream>
using namespace std;
int main( int argc, // Number of strings in array argv
char *argv[]) // Array of command-line argument strings
{
int count;
// Display each command-line argument.
cout << "\nCommand-line arguments:\n";
for( count = 0; count < argc; count++ )
cout << " argv[" << count << "] " << argv[count] << "\n";
}
If you name this application «Text.exe» and you want to pass arguments 1 to 4 to it, then you should call it like this:
"Text.exe" argument1 argument2 argument3 argument4
For the application this means that argc=5 and argv = {«Text.exe», «argument1», «argument2″,»argument3″,»argument4»}
Parsing the command line arguments
We have processed the C++ application command line arguments above, but if we want to be able to actually compare and use it to make decisions inside our application then we will need to parse the arguments.
Here is an example using std::string to parse our command line arguments into an string that then we can compare and process. In this example, only one argument, named «argument», is passed to the program.
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
std::string input(argv[1]);
if(input=="argument"){
cout << "Do what is needed here";
}
}
And that’s it! once you’re able to parse the commands then it’s up to you to decide how to design your application and how you would like the command line arguments to be passed into your program.
Good luck!