How to Use Main Arguments in C++

Muzaffer Arda Uslu
Oct 25, 2020 · 2 min read

Hi there, my name is Muzaffer Arda Uslu. I am a computer engineering student at Eskişehir Osmangazi University.

This article I’m gonna show how can we use main function’s arguments in C++.

Firstly, let’s learn ‘argc’.
argc contains the number of arguments passed to the program and also it is short way for “argument count”. Every C++ program has one argument at least. Then this argument is our .exe file.

So, what is ‘argv’?
argv is the name of the variable argv stands for “argument vector”. A vector is a one-dimensional array and argv is a one-dimensional array of strings.

I’m gonna show an example program.

Create a C++ project and let’s put a name “bohemian-rhapsody” for project and our .exe file’s name will be “bohemian-rhapsody.exe”. In this way, our argv array’s first index is “bohemian-rhapsody.exe”.

We have two .txt files. They are “read.txt.” and “write.txt”.

“write.txt” is empty.

The program reads “read.txt” file and writes what it reads to the “write.txt”.

We set the three files from cmd for this program.

Go to bohemian-rhapsody.exe’s folder in file explorer.

X:\….\repos\bohemian-rhapsody\Debug

Click to path and type “cmd” then press enter.

We have three argument. They are “bohemian-rhapsody.exe”, “read.txt” and “write.txt”.

argv array

Find in order this files with TAB key and press enter. After pressing the program starts.

Here is the program’s code:

Bilgisayar ve Bilişim Teknolojileri Kulübü

Bilgisayar ve Bilişim Teknolojileri Kulübü Medium Yayını