Parsing Command Line Parameters in C++ Program



In this article, we will learn how to pass command line parameters in C++. The command line argument is a parameter that is passed to a program when it is invoked by the command line or terminal.

Parsing Command Line Parameters in C++

In C++, we can pass the command line argument using the argc and argv[] parameters that are passed to the main function.

Where argc refers to the number of arguments passed, and argv[] is a pointer array that points to each argument passed to the program.

We can use loops to iterate and parse the command line parameter stored inside the argv array.

C++ Program to Parse Command Line Parameters

Following is a simple example that checks if there is any argument supplied from the command line and takes action accordingly:

#include <iostream>
using namespace std;
int main( int argc, char *argv[] ) {
   if( argc == 2 ) {
      cout << "The argument supplied is "<< argv[1] << endl;
   } else if( argc > 2 ) {
      cout << "Too many arguments supplied." <<endl;
   }else {
      cout << "One argument expected." << endl;
   }
}

Following is the output:

One argument expected.
Updated on: 2025-06-10T18:52:52+05:30

304 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements