Command Line Arguments:
Command line arguments are values or options provided to a program at the time of its execution. When a program is run from the command line or terminal, additional information can be passed to the program by specifying command line arguments. These arguments are typically used to configure the behavior of the program or to provide input data.
In C++ (and many other programming languages), the main function can accept command line arguments. The argc parameter represents the number of arguments, and the argv parameter is an array of strings containing the actual argument values.
Here's a simple example in C++:
cpp
Copy code
#include iostream
int main(int argc, char* argv[]) {
// argc: Number of command line arguments
// argv: Array of strings containing command line arguments
std::cout "Number of arguments: " argc std::endl;
// Display each command line argument
for (int i = 0; i argc; ++i) {
std::cout "Argument " i ": " argv[i] std::endl;
}
return 0;
}
In this example:
argc is an integer representing the number of command line arguments.
argv is an array of strings (char*) containing the actual command line arguments.
argv[0] typically holds the name of the program itself.
When you run this program from the command line, you can provide additional arguments. For example:
bash
Copy code
./program_name arg1 arg2 arg3
In this case, argc will be 4 (including the program name), and argv will be an array containing the program name and the provided arguments.
Example Usage:
Suppose you want to create a program that calculates the sum of two numbers provided as command line arguments:
cpp
Copy code
#include iostream
#include cstdlib // For atoi function
int main(int argc, char* argv[]) {
if (argc != 3) {
std::cerr "Usage: " argv[0] " num1 num2" std::endl;
return 1; // Exit with an error code
}
// Convert command line arguments to integers
int num1 = std::atoi(argv[1]);
int num2 = std::atoi(argv[2]);
// Calculate and display the sum
int sum = num1 + num2;
std::cout "Sum: " sum std::endl;
return 0;
}
This program checks whether it has exactly three command line arguments (including the program name). If not, it displays an error message. It then converts the provided arguments to integers and calculates their sum.
When running the program:
bash
Copy code
./sum_program 5 7
The output will be:
makefile
Copy code
Sum: 12
Keep in mind that the atoi function is used here for simplicity. For more robust argument parsing, you might consider using a dedicated library or more advanced techniques depending on your specific needs.