Command Line Arguments in C++

Command-line arguments are a common way to parameterize execution of programs. For example, ./program arg1 arg2 passes arg1 and arg2 as arguments to the program.

#include <iostream>
#include <vector>

int main(int argc, char* argv[]) {
    // argc provides the number of command-line arguments
    // argv is an array of C-style strings containing the arguments

    // Create a vector to store all arguments, including the program name
    std::vector<std::string> argsWithProg(argv, argv + argc);

    // Create a vector to store arguments without the program name
    std::vector<std::string> argsWithoutProg(argv + 1, argv + argc);

    // You can get individual args with normal indexing
    std::string arg = argc > 3 ? argv[3] : "";

    // Print the arguments
    std::cout << "All arguments (including program name):" << std::endl;
    for (const auto& arg : argsWithProg) {
        std::cout << arg << " ";
    }
    std::cout << std::endl;

    std::cout << "Arguments without program name:" << std::endl;
    for (const auto& arg : argsWithoutProg) {
        std::cout << arg << " ";
    }
    std::cout << std::endl;

    std::cout << "Fourth argument (if available): " << arg << std::endl;

    return 0;
}

To experiment with command-line arguments, it’s best to compile the program first.

$ g++ -std=c++11 command_line_arguments.cpp -o command_line_arguments
$ ./command_line_arguments a b c d
All arguments (including program name):
./command_line_arguments a b c d 
Arguments without program name:
a b c d 
Fourth argument (if available): d

In C++, command-line arguments are passed to the main function through the argc (argument count) and argv (argument vector) parameters. argc is an integer that represents the number of arguments, and argv is an array of C-style strings (char*) containing the arguments.

The first element of argv (index 0) is always the name of the program itself. The actual command-line arguments start from index 1.

In this example, we use C++ standard library containers and algorithms to handle the arguments more easily:

  1. We create a vector<string> called argsWithProg that includes all arguments, including the program name.
  2. We create another vector<string> called argsWithoutProg that includes only the command-line arguments, excluding the program name.
  3. We demonstrate how to access an individual argument by index.
  4. We print all the arguments to show how they can be accessed and manipulated.

This approach provides a more C++-idiomatic way of handling command-line arguments compared to directly using argc and argv.

Next, we’ll look at more advanced command-line processing with option parsing libraries in C++.