C++ — Command Line Arguments

Jake Cutter
Technology Hits
Published in
2 min readJan 18, 2022

Within your executable code, we have arguments we can add to the run command on our machine that tells it to use this file in the code we are about to use. For example, if you want to invert the colors for an image you have to include the image file that you are trying to invert and a new file that the inverted image will be. This is done through the command line.

Photo by AltumCode on Unsplash

Location of Command Arguments

Your command arguments will go on your main function. Your main function is where your code starts to execute and where you call on the other functions outside of main like classes, structs, and individual functions for specific use.

Example:

int main(int argc, char** argv){}

You will use the variables argc & argv in your code conditions and file opening.

How to use Command Arguments

You use command arguments to interact with files you want to be used for your code. For example, the inverted picture. You add said file using the command

fin.open(argv[1]);

You must include the library fstream, cstring, and sstream on your includes.

#include <fstream>

#include <sstream>

#include <cstring>

#include <iostream>

This will open the first argument you plugged into the executable on VIM or the command line. argv[0] is the run file that you start with the slash.

./code_name argv[1] argv[2] …

You should always error-check that the file does open. You use the command perror.

Example:

ifstream fin;

if(!fin.is_open){

perror(argv[1]);

return(1);

}

Explanation:

The executing file fin gets error checked using your first argument argv[1] by the perror command or print error.

Checking the User’s Arguments

When you run the executables you need to also check the user arguments to make sure that they applied the correct number and type of files so that your code runs properly.

Example:

if(argc < 2){

cerr << “Usage: “ << argv[0] << “Text” << endl;

}

Explanation:

argc < 2: This condition says that the added arguments have to be less than 2. The arguments are the argv. Your arguments need to add up to the condition in the if loop.

Usage: The usage message lets the user of the code know what they need to type in in order to execute your code. This is done through the cerr command.

Citations:

Marz, Stephen. Professor. University of Tennessee. Knoxville, Tennessee. 2021

--

--