Site icon TestingDocs.com

C++ Command Line Arguments

Overview

In this tutorial, we will learn how to specify and process command line arguments to C++ programs.

Command-line arguments are values supplied from the command line, after the C++ program name. C++ language allows the user to specify values on the command line when the program is run so that it is easy to alter the runtime behavior of the program.

main() function

We can process the command line arguments using the below main function with arguments as:

int main(int argc, char* argv[])
{
//C++ code
}

argc

This argument is the count of the arguments. It tells how many command-line arguments were passed. Note that this count includes the
program pathname as well.

argv[]

This argument represents an array of pointers to an array of strings. The strings are the arguments that include the program name as well.

C++ Program

Sample C++ program to print the command line arguments.

/* ************************************************
 * Sample C++ Program on Linux 
 * Print CommandLine Arguments C++ Program
 * C++ Tutorials - www.TestingDocs.com
 *************************************************/

#include<iostream>
using namespace std;

int main(int argc, char *argv[])
{
	cout << "Number of command line arguments[This includes program path] = " << argc << endl;
    for(int i=0;i< argc;i++)
        cout << argv[i] << endl;
	return 0;
}


 

Sample Output

C++ Tutorials

C++ Tutorials on this website:

https://www.testingdocs.com/c-coding-tutorials/

For more information on the current ISO C++ standard

https://isocpp.org/std/the-standard

Exit mobile version