Retrieving Command Line Arguments in C++

To access all the command line arguments that are passed from the command line when the program gets executed we can use the main function’s parameters i.e. (int argc, char *argv[]) that are passed in the main function definition.

Here,

  • argc: It denotes the number of arguments passed.
  • argv: It is the actual arguments that are contained in an array of character strings called argv.

We can use a loop, such as a for loop, to iterate over the argument vector that continues until the loop variable is less than argc. During each iteration, print each argument value using the array notation – argv[index] to the console to display all command-line arguments passed to the program.

C++ Program to Retrieve Command Line Arguments

The below example demonstrates how we can retrieve command line arguments in C++.

C++
// C++ program to retrieve command line argument

#include <iostream>
using namespace std;

// Main function wiht parameters argc and argv
int main(int argc, char* argv[])
{
    // Printing the count of command-line arguments.
    cout << "Number of arguments: " << argc << endl;

    // Iterating through each argument and print its index and
    // value.
    for (int i = 0; i < argc; i++) {
        cout << "Argument " << i << ": " << argv[i] << endl;
    }
    return 0;
}


Input

./myProgram C++ is Programming Language

Output

Number of arguments: 5
Argument 0: ./myprogram
Argument 1: C++
Argument 2: is
Argument 3: Programming
Argument 4: Language

How to Retrieve Command-Line Arguments in C++?

Command-line arguments are the values or parameters that are passed after the name of the program through the command line or terminal when the program is executed. In this article, we will learn how to retrieve command-line arguments in C++.

Similar Reads

Retrieving Command Line Arguments in C++

To access all the command line arguments that are passed from the command line when the program gets executed we can use the main function’s parameters i.e. (int argc, char *argv[]) that are passed in the main function definition....