Programs are often launched from the console and need input parameters to control their behavior. This page is a compact guide to passing and processing such parameters in C++.
In C++, parameters are passed via the main function using the standard signature:
int main(int argc, const char* argv[]) {}
argc (Argument Count) — the number of arguments passed.
argv (Argument Vector) — the arguments as strings.
argv[0] is always the path to the executable.
The first user-supplied value is in argv[1], the second in argv[2], and so on.
#include "pch.h"
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
int main(int argc, const char* argv[]) {
cout << endl << "Path to this executable:" << endl;
cout << argv[0] << endl << endl;
if (argc > 1) {
cout << "First input parameter:" << endl;
cout << argv[1] << endl << endl;
} else {
cout << "No input parameter supplied." << endl << endl;
}
return 0;
}
Example call from PowerShell:
c:\<pathtoexe>\test.exe "thisismy inputvalue"
H@ppy H@cking