C++ Tutorials


Command Line Arguments

Tutorials > C++ > Command Line Arguments

View Full Source

What are Command Line Arguments?

A command line argument is an additional parameter that you enter when executing a program. If your executable file was called main.exe, you could type something similar to :

    main.exe Arg1 Arg2

This would send the two arguments to your program.

Contents of main.cpp :

#include <iostream>
#include <stdlib.h>

using namespace std;

To enable command line arguments, you need to add two parameters to your main function. The first parameter is an integer and is normally specified as argc. This value specifies the number of arguments entered - 1. There is always one argument which is the name of the executable file.
The second parameter is an array of character strings and is usually specified as argv The first element is the name of the executable file and the rest are the arguments that were entered.

int main(int argc, char *argv[])

We first check to see if argc is equal to 1. If it is then we know that no arguments were entered.

	if (argc == 1)
		cout << "No arguments given" << endl;

If there are arguments, we loop through all character strings in argv and output their values. You will notice that the first argument entered is equal to main.exe. If you wish to enter a single argument with spaces in it, you need to encase it in quotes otherwise it will be read as more than one argument.

		for (int i = 0; i < argc; i++)
			cout << argv[i] << endl;


	return 0;

You should now be able to pass command line arguments to your programs. As you can see, it is extremely simple to accomplish this and it could enhance your program greatly.

Please let me know of any comments you may have : Contact Me

Source Files : Visual Studio Dev-C++ Unix / Linux

< Tutorial 29 - Typecasting Tutorial 31 - Enumerations >

Back to Top

All Rights Reserved, © Zeus Communication, Multimedia & Development 2004-2005

Read the Disclaimer