Command Line Arguments in C++

Command line arguments in C++ allow you to pass values to a program when it's executed from the command line. These arguments are often used for configuration, input data, or specifying the behavior of the program.

Accessing Command Line Arguments

In C++, command line arguments are provided as parameters to the main function. The main function can take two parameters:

  1. int argc: The number of command line arguments passed to the program, including the program name itself.
  2. char* argv[]: An array of C-style strings (character arrays) representing the command line arguments.
#include <iostream> int main(int argc, char* argv[]) { std::cout << "Number of command line arguments: " << argc << std::endl; for (int i = 0; i < argc; i++) { std::cout << "Argument " << i << ": " << argv[i] << std::endl; } return 0; }

Running the Program

If you compile the above program and run it from the command line like this:

./my_program arg1 arg2 arg3

The output will be:

Number of command line arguments: 4 Argument 0: ./my_program Argument 1: arg1 Argument 2: arg2 Argument 3: arg3

Using Command Line Arguments

You can use command line arguments to customize the behavior of your program. For instance, you can pass file names, options, or configuration parameters to your program from the command line.

#include <iostream> int main(int argc, char* argv[]) { if (argc == 1) { std::cout << "No command line arguments provided." << std::endl; } else { std::cout << "Command line arguments provided:" << std::endl; for (int i = 1; i < argc; i++) { std::cout << "Argument " << i << ": " << argv[i] << std::endl; } } return 0; }

Running the Program

If you run the program without any command line arguments:

./my_program

The output will be:

No command line arguments provided.

If you run the program with arguments:

./my_program file.txt -v

The output will be:

Command line arguments provided: Argument 1: file.txt Argument 2: -v

Conclusion

Command line arguments in C++ are values passed to a program when it is executed from the command line. These arguments are accessible through the main function, with argc representing the number of arguments and argv containing the argument values as an array of C-style strings. They enable the customization and configuration of programs based on user input and are often used for tasks like specifying file names or setting program options.