7.13 — Command line arguments

As you learned in the introduction to development lesson, when you compile and link your program, the compiler produces an executable file. When a program is run, execution starts at the top of the function called main(). Up to this point, we’ve declared main like this:

Notice that this version of main() takes no parameters. However, many programs need some kind of input to work with. For example, let’s say you were writing a program called WordCount to count the number of words in a text file. What text file should be read and processed? The user has to have some way of telling the program which file to open. To do this, you might take this approach:

However, there is a major problem with this approach. Every time the program is run, the program will wait for the user to enter input. That means execution of the program can not be automated very easily. For example, if you wanted to run this program on 500 files every week, the program would stop and wait for you to enter a new filename each and every time it was run. And you’d have to do so by hand.

Command line arguments

For programs that have minimal and/or optional inputs, command line arguments offer a great way to make programs more modular. Command line arguments are optional string arguments that a user can give to a program upon execution. These arguments are passed by the operating system to the program, and the program can use them as input.

Programs are normally run by invoking them by name. On the command line, to run a program, you can simply type in its name. For example, to run the executable file “WordCount” that is located in the root directory of the C: drive on a Windows machine, you could type:


In order to pass command line arguments to WordCount, we simply list the command line arguments after the executable name:

C:\>WordCount Myfile.txt

Now when WordCount is executed, Myfile.txt will be provided as a command line argument. A program can have multiple command line arguments, separated by spaces:

C:\>WordCount Myfile.txt Myotherfile.txt

This also works for other command line operating systems, such as Linux (though your prompt and directory structure will undoubtedly vary).

If you are running your program from an IDE, the IDE should provide a way to enter command line arguments. For example, in Microsoft Visual Studio 2005, right click on your project in the solution explorer, then choose properties. Open the “Configuration Properties” tree element, and choose “Debugging”. In the right pane, there is a line called “Command Arguments”. You can enter your command line arguments there for testing, and they will be automatically passed to your program when you run it.

Now that you know how to provide command line arguments to a program, the next step is to access them from within our C++ program. To do that, we use a different form of main() than we’ve seen before. This new form of main() takes two arguments (named argc and argv by convention) as follows:

You will sometimes also see it written as:

Even though these are essentially the same, we prefer the first representation because it’s intuitively easier to understand.

argc is an integer parameter containing a count of the number of arguments passed to the program (think: argc = argument count). argc will always be at least 1, because the first argument is always the name of the program itself! Each command line argument the user provides will cause argc to increase by 1.

argv is where the actual arguments themselves are stored. Although the declaration of argv looks intimidating, argv is really just an array of C-style strings. The length of this array is argc.

Let’s write a short program to print the value of all the command line parameters:

Now, when we invoke this program with the command line arguments “Myfile.txt” and “100”, the output will be as follows:

There are 3 arguments:
0 C:\WordCount
1 Myfile.txt
2 100

Argument 0 is always the name of the current program being run. Argument 1 and 2 in this case are the two command line parameters we passed in.

Back to our previous example, let’s go ahead and partially write WordCount so it uses command line arguments instead of asking the user for input:

Now, when WordCount is run, it will not require any user interaction. This means we can have a batch file, script, or even another program run WordCount many times in a row (with different command line arguments) in an automated manner.

Those of you studying computer science in school (or planning on taking programming classes) may find that your professors ask you to use command line arguments to provide inputs to the program rather than using cin. Running each student’s program (when there are 50 or 100 students) and having to type in the same filenames or inputs to test whether the program works makes for slow grading and is tedious to boot. By using command line arguments, professors and TAs can automate the process of running the student’s programs on a preselected set of inputs, using another program to compare whether the output matches known correct output. This can speed up the overall grading process immensely.

7.14 -- Ellipses (and why to avoid them)
7.12 -- Handling errors (assert, cerr, exit, and exceptions)

25 comments to 7.13 — Command line arguments

  • Suresh

    I am trying to find a word using the command line (./wordsearch two < samplefile.txt).
    Please let me know if the above code can get me these results. My results should display
    "word two found in the file"
    "word two found in the second line"

    *** Is it possible to find two words using the above command line

    samplefile.txt contains

  • momalok

    Hi Alex.
    Firstly great site!
    But im having a few problems on passing command line arguments. I have copied and pasted various examples and tried running my program (microsoft visual studio express 2010), but it does not allow the user to enter any program name or filename, and immediately just exits with error code File not found.
    When i add command line arguments through properties debugging in visual studio, it works fine for one program, but not for more than one for some reason.
    If i need to add more arguments to the program, then do i need to add one to argc each time, so that if (argc < 3) for 3 arguments etc?
    and also do i need to modify the following line because surely each additional argument points to the next array element?
    ifstream myfile(argv[1]);
    In conclusion i am pretty confused!

  • lukecui

    it's a grate site, i also found something about this example used with _tmain, please check

  • yiangom

    Excellent way of explaining things, thank you very much.
    I would like to ask you something, as I am not sure what the advantage of using command line arguments instead of user input is.
    You are saying: " For example, if you wanted to run this program on 500 files every week, the program would stop and wait for you to enter a new filename each and every time it was run. " If you use command line arguments, you would have to put 500 filenames as arguments, right?
    C:\\>WordCount Myfile1.txt ...... Myfile500.txt

    How is this better than the user inputing the filenames?


    Double quotes(") are not taken as command line arguments.
    Only way to inclde double quotes is preceeding quotes with '\'.Eg. \"

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">