Command Line Args in C++

As you’re already familiar with, when you call some functions, you need to pass arguments to them.  So, what about main?  There are two different function headers for he main method in C++ that we can use:

int main (); //header 1

and

int main(int argc, char* argv[]); //header 2

Now, you should ask yourself, “What’s the difference?”  Remember that when you execute a program (either from the command line or by double-clicking on an icon or something similar), you’re really asking the OS to load the executable and begin execution.  When the OS is starting your program, you can use command line arguments to send arguments into the main method.  Consider this program execution:

./myFunGame input.txt output.txt

Conceptually, what you’re saying is that the program called myFunGame needs two pieces of information in order to properly execute.  These two pieces of information are “input.txt” and “output.txt” for this execution.  But, next time you run the program, you might want to send “highData.in” and “lowData.txt”.  Another way you might perhaps achieve the same thing is to start the program and then ask the user (via prompts with cout, and reading data with cin) to input the name of two files.  Command-line arguments just automates that process in a sense.

In the example execution above (myFunGame), it would use the main method header that takes two arguments (labeled as Header 2 above). argc would get the value 3, and argv would get {“/some/path/to/myFunGame”, “input.txt”, and “output.txt”} (it would technically be a pointer to an array containing those 3 c-strings).

//Simple example of printing out the command line
//arguments passed to the main method
//
//programmer: Mark Fontenot
#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{
    cout << endl << endl;
    for (int i = 0; i < argc; i++)
        cout << "arg[" << i << "] = " << argv[i] << endl;
    cout << endl << endl;
    return 0;
}

Speak Your Mind

*

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.