Passing Command Line Parameters to C++ Project from Console Window

Passing Command Line Arguments to a C++ Console Application is really easy and quick, provided you do understand how the C++ Application accepts them. In lots of projects on this website containing sample C++ projects, the function

int _tmain(int argc, _TCHAR* argv[])

has been used and described as entry point of the program. In order to pass parameters to the program from console window, all you need to do is pas the parameters from the console window and read the passed in parameters from the function arguments as displayed in the sample c++ project code below.

Sample C++ Code to Pass Command Line Parameters

Sample C++ Code to Pass Command Line Parameters

Note that the sample C++ code displays the number of arguments passed in and then displays all the parameters using a for loop onto the console window. The output of this program depends on what command line arguments you pass it in when the application is run. The given below screenshot displays the command line parameters passed in and output of the sample C++ project code.

Parameter Passing to a Console C++ Application from Command Line

Parameter Passing to a Console C++ Application from Command Line

When running this sample application, the project was compiled with Multi Byte Character Set instead of using Unicode Character Set. The Character Set for the project was modified using the Visual Studio Project Menu – > CommandLineParameters Properties. The Properties of any project in Visual Studio can also be viewed using Alt + F7 keyboard shortcut. The Project properties were modified so that character set of this project was Multi Byte Character Set as displayed in the screenshot below.

C++ Project Properties of Command Line Parameters Project using Multi Byte Character Set

C++ Project Properties of Command Line Parameters Project using Multi Byte Character Set

The Project properties in Visual Studio allows you to view or modify other parameters related to the project loaded. The sample code for this project is provided as below, feel free to experiment with the code and understand how you can make your C++ Application aware of Command Line Arguments.

// CommandLineParameters.cpp : Defines the entry point for the console application.//Visit TapKaa.com for more C++ Tutorials#include "stdafx.h"#include <iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){cout << "In Total There were " << (argc-1) << " Command Line Arguments.n";for(int vl_iIndex=1;vl_iIndex<argc;vl_iIndex++){cout << "Parameter Number " << vl_iIndex << " Had the Value " << argv[vl_iIndex] << ".n";}return 0;}