How to access command-line arguments in C++

Samara Augustin
2 min readNov 19, 2020

When I first learned how to code in C++ there were many variables and components I struggled with. One of the intimidating topics was how to access command-line arguments. At first, I was confused about its purpose and how to utilize it. However, after countless tutorials and reading several articles, I was able to comprehend its meaning and function in computer science.

This is what I obtained from the topic:

Command-line arguments are accessed through the main function line, the format that is commonly used is shown below:

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

{

}

The amount of words written in the command-line, which are separated by space(s), is the number of arguments you can use. For example, if there’s only one argument in the command-line which is a text file called “example.txt”, in order to access the text file name you would have to follow the following steps. First, you would check whether there is an argument in the command-line by using an “if” statement.

It can be checked by either writing:

if (argc == 1)

{

}

or:

if (argc > 1)

{

}

The first code would check if there are no arguments in the command-line while the second would check whether there are any arguments in general. If there happens to be an argument in the command-line, which according to the previous example, there is, then the second “if” statement will be fulfilled.

Secondly, in order to use a specific argument in your code, you would use the following format:

argv[n]

where “n” represents the place of the command line argument you want to use.

Based on our example, the first command-line argument that was entered was “example.txt”, therefore in order to access it you would need to use this statement:

argv[1]

By using this method you can write a program to open up the file, “example.txt”, which was specified in the argument, to read or write to the contents in the file. In conclusion, now that you have a way to access the command-line argument, you can use the argument to do whatever you want.

I hope this helped and thanks for reading!

--

--