Command Line Arguments

So far, we’ve always run our C++ programs by typing “.\main” into our terminal. When doing this, we’re also able to follow “.\main” with additional information for our program to use. To do this, the main function needs to be given two parameters:

int main(int argc, char *argv[]) {
    //Code here...
}
  • argc” (argument count) is the number of space-separated words in the command used to run the program.
    • For example, running a program with “.\main This is a test.” would result in the argc parameter having a value of 5 (for there being 5 space-separated words, including “.\main“).
  • argv” (argument vector) is an array of each space-separated word in the command used to run the program. Each element in this array is a C-style string using the “char *” data type.
    • Because an array can be represented as a pointer to its first element, this second parameter may sometimes be typed as “char **argv” (a pointer to a pointer of a char).
    • As an example, running a program with “.\main This is a test.” would result in the argv parameter having a value of {".\main", "This", "is", "a", "test."}.

Here’s a full program using command line arguments:

#include <iostream>

int main(int argc, char *argv[]) {
    std::cout << "You've entered " << argc << " argument(s):\n";
    for (int i = 0; i < argc; i++) {
        std::cout << argv[i] << "\n";
    }
    return 0;
}

When running this program with “.\main This is a test.“, the program’s output is:

You've entered 5 argument(s):
.\main
This
is
a
test.

Challenge Problem

Write a program that takes your first and last name as arguments and uses those to print “Hello [first name] [last name]!”. Print a different message if the number of arguments provided is invalid.

If you get stuck, check out my solution here.