How to Parse Command Line Arguments in C++?
Last Updated :
27 Feb, 2024
In C++, command line arguments are parameters that are passed to a program when it is invoked via command line or terminal. In this article, we will learn how to parse command line arguments in C++.
Parse Command Line Arguments in C++
In C++, we can parse the command-line arguments using the argc
and argv[]
parameters that are passed to the main
function.
argc
represents the number of command line arguments passed to the program,
argv
is an array of C-style strings (character arrays) containing the actual arguments.
We can use loops to iterate and parse the command line arguments stored inside the argv array.
C++ Program to Parse Command Line Arguments
C++
#include <iostream>
using namespace std;
int main( int argc, char * argv[])
{
cout << "You have entered " << argc
<< " arguments:" << endl;
int i = 0;
while (i < argc) {
cout << "Argument " << i + 1 << ": " << argv[i]
<< endl;
i++;
}
return 0;
}
|
Input:
./program1 this is something
Output:
You have entered 4 arguments:
Argument 1: ./program1.out
Argument 2: this
Argument 3: is
Argument 4: something
Share your thoughts in the comments
Please Login to comment...