The Wayback Machine - https://web.archive.org/web/20240822172613/https://www.geeksforgeeks.org/command-line-arguments-in-cpp/
Open In App

Command Line Arguments in C++

Last Updated : 25 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Command-line arguments are arguments that are passed to a program when it is executed from the command line or terminal. They are provided in the command-line shell of operating systems with the program execution command.

The main function of C++ generally can have the following signature:

int main(){

// Suitable Code

return 0;

}

But to pass command-line arguments, we typically define main() with two arguments, where the first argument is the number of command-line arguments and the second is the list of command-line arguments.

Signature of main() Function for C++ Command Line Arguments

int main(int argc, char *argv[]){
// Suitable Code
return 0;
}

What is argc?

The variable argc (ARGument Count) is an integer that stores the number of command line arguments passed to the main function. It also includes the count for the name of the program, so if we pass a value to a program, the value of argc would be 2 (one for argument and one for program name).

What is argv?

The array argv (ARGument Vector) is an array of C-style strings like (‘char*’) where every element points to a command line argument. argv does not store the actual argument, but the pointer to that argument. The argv[0] will always contain the name of the program.

Example of Command Line Argument in C++

C++




// C++ program to demonstrate the use of command line
// arguments
#include <iostream>
using namespace std;
  
int main(int argc, char* argv[])
{
    cout << "You have entered " << argc
         << " arguments:" << endl;
  
    // Using a while loop to iterate through arguments
    int i = 0;
    while (i < argc) {
        cout << "Argument " << i + 1 << ": " << argv[i]
             << endl;
        i++;
    }
  
    return 0;
}


Input

./program1 hello geeks

Output

You have entered 3 arguments:
Argument 1: ./program1
Argument 2: hello
Argument 3: geeks

Properties of Command Line Arguments in C++

  • The argc is an integer that stores the number of command line arguments.
  • The argv store is an array of pointers to characters that stores the command line arguments.
  • The first element in argv (argv[0]) contains the name of the program itself.
  • Only string values are passed through the command line argument.
  • Multiple arguments are separated by a whitespace. To pass a single argument with some whitespace, we use
  • The argv[1] points to the first command line argument and argv[argc-1] points to the last argument. argv[argc] is NULL.

Command Line Arguments in Different Scenarios

The following programs illustrate the behaviour of C++ program for different kinds of command line arguments.

Multiple Command Line Arguments

In the following program, we pass three arguments to the main function from the command line.

C++




// C++ program for passing multiple command line arguments
#include <iostream>
using namespace std;
  
int main(int argc, char* argv[])
{
    if (argc >= 2) {
  
        // printing number of arguments
        cout << "Number Of Arguments Passed: " << argc
             << endl;
        cout << "----Following Are The Command Line "
                "Arguments Passed----"
             << endl;
  
        // printing all the arguments
        for (int i = 0; i < argc; ++i) {
            cout << "argv[" << i << "]: " << argv[i]
                 << endl;
        }
    }
    return 0;
}


Terminal Command:

$ ./program one two three

Output:

Number Of Arguments Passed: 4
----Following Are The Command Line Arguments Passed----
argv[0]: ./program
argv[1]: one
argv[2]: two
argv[3]: three

Passing Space Seperated String as a Single Argument

In C++ program, multiple command line arguments are passed to the function by separating them by a whitespace but what happens if you have to pass an argument string that already contains spaces. In such case, we can enclose that string in the double quotes to pass it as a single argument.

C++




// C++ program to illustrate the spaces seperated string as
// a single argument
#include <iostream>
using namespace std;
  
int main(int argc, char* argv[])
{
    cout << "Program Name Is: " << argv[0] << endl;
  
    if (argc >= 2) {
        cout << "Number Of Arguments Passed: " << argc
             << endl;
        cout << "----Following Are The Command Line "
                "Arguments Passed----"
             << endl;
        cout << "argv[0]: " << argv[0] << endl;
        cout << "argv[1]: " << argv[1] << endl;
    }
  
    return 0;
}


Terminal Command:

$ ./solution.out 'one two three'

Output:

Program Name Is: ./solution.out
Number Of Arguments Passed: 2
----Following Are The Command Line Arguments Passed----
argv[0]: ./solution.out
argv[1]: one two three


Similar Reads

Equation of straight line passing through a given point which bisects it into two equal line segments
Given a straight line which passes through a given point (x0, y0) such that this point bisects the line segment in two equal line segments. The task is to find the equation of this straight line.Examples: Input: x0 = 4, y0 = 3 Output: 3x + 4y = 24Input: x0 = 7, y0 = 12 Output: 12x + 7y = 168 Approach: Let PQ be the line and AB be the line segment b
4 min read
Default Arguments and Virtual Function in C++
Default Arguments are the values provided during function declaration, such that values can be automatically assigned if no argument is passed to them. In case any value is passed the default value is overridden and it becomes a parameterized argument. Virtual function is a member function that is declared within a base class and is redefined(Overr
3 min read
Default Arguments in C++
A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden. 1) The following is a simple C++ example to demonstrate the use of default arguments. Here, we don't have to w
5 min read
Template non-type arguments in C++
Prerequisite: Templates in C++ Generally, a C++ template, with a single argument looks like this: template&lt;typename template_name&gt; But it has been seen that a template can have multiple arguments. The syntax for the same would be: template&lt;class T1, class T2, class T3, ........., class Tn&gt; where, n is the number of arguments. It is also
3 min read
Templates and Default Arguments
Default parameters for templates in C++: Like function default arguments, templates can also have default arguments. For example, in the following program, the second parameter U has the default value as char. #include&lt;iostream&gt; using namespace std; template&lt;class T, class U = char&gt; class A { public: T x; U y; }; int main() { A&lt;char
1 min read
Some Interesting facts about default arguments in C++
Predict the output of following C++ programs. 1) #include &lt;iostream&gt; void init(int a=1, int b=2, int c=3); int main() { init(); return 0; } void init(int a=1, int b=2, int c=3) { std::cout &lt;&lt; a &lt;&lt; ' ' &lt;&lt; b &lt;&lt; ' ' &lt;&lt; c; } The above program looks correct at first glance but will fail in compilation. If function use
1 min read
When Do We Pass Arguments by Reference or Pointer in C++?
In C++, we can pass arguments to a function as a value, reference (or pointer). Each method has its unique benefits and uses. In this article, we will discuss the application or cases where we should pass the arguments by reference or a pointer. But first, let’s quickly revisit the definitions of pointers and references. Pointers in C++ Pointers ar
4 min read
Pause Command in C++
pause() is a C++ method used to pause a program during execution. It allows the user to input or read data. The pause approach makes the system more readable and user-friendly by allowing the user to read the instructions before performing any task. What is pause()?The pause() function is used to pause the execution of the current program and wait
3 min read
Command Injection Vulnerability and Mitigation
Command injection is basically injection of operating system commands to be executed through a web-app. The purpose of the command injection attack is to inject and execute commands specified by the attacker in the vulnerable application. In situation like this, the application, which executes unwanted system commands, is like a pseudo system shell
3 min read
Draw a line in C++ graphics
graphics.h library is used to include and facilitate graphical operations in program. graphics.h functions can be used to draw different shapes, display text in different fonts, change colors and many more. Using functions of graphics.h you can make graphics programs, animations, projects and games. You can draw circles, lines, rectangles, bars and
2 min read
Number of ways to choose K intersecting line segments on X-axis
Given an array arr[] of line segments on the x-axis and an integer K, the task is to calculate the number of ways to choose the K line-segments such that they do intersect at any point. Since the answer can be large, print it to modulo 10^9+7. Examples: Input: arr[] = [[1, 3], [4, 5], [5, 7]], K = 2 Output: 2 Explanation: The first way to choose [1
10 min read
Swap Two Variables in One Line
We have discussed different approaches to swap two integers without the temporary variable. How to swap into a single line without using the library function?1) Python: In Python, there is a simple and syntactically neat construct to swap variables, we just need to write "x, y = y, x".2) C/C++: Below is one generally provided classical solution: //
4 min read
Line Splicing in C/C++
While writing a program, sometimes we give comment about the working of the code in the comment section with the help of single/double comment line. But we had never thought that if at the end of this comment line if we use \(backslash) character then what will happen?The answer of the above question is line Splicing. Lines terminated by a \ are sp
2 min read
Line Intersection in C++
Line Intersection in C++ is a problem that involves finding the point of intersection of two lines. For given points X and Y that corresponds to line XY and points A and B that corresponds to line AB the task is to find whether two lines (XY and AB) intersect and find the intersection point if they do. Example: Input : X = (2, 3), Y = (5, 7)A = (3,
5 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
30 OOPs Interview Questions and Answers (2024)
Object-Oriented Programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
C++ Interview Questions and Answers (2024)
C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent in C++. It is utilized by top IT companies such as
15+ min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is &lt;string&gt;. The substring function takes two values pos and len as an argument
8 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
9 min read
Priority Queue in C++ Standard Template Library (STL)
A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}). In C++ STL, the top elemen
11 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
10 min read
Set in C++ Standard Template Library (STL)
Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific sorted order i.e. either ascending or descending. The std::set class is the part of C++ Standard Template Library (STL) and it is defined inside the &lt;set&gt; header file. Syntax: std:
7 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the &lt;map&gt; header file. Basic std::map Member FunctionsSome basic functions associated with std::
8 min read
The C++ Standard Template Library (STL)
The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms, and iterators. It is a generalized library and so, its components are parameterized. Working knowledge of template classes is a prerequ
5 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
9 min read
Templates in C++ with Examples
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types. Rather than writing and maintaining multiple codes, we can write one sort() and pass the dat
10 min read
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the
6 min read
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time an object of a class is created. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor
7 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
three90RightbarBannerImg