Lesson 204 +10 XP

Command Line Arguments

Command Line Arguments

A program can receive inputs from the command line. The entry point sees them as argc (argument count) and argv (argument values).

The signature

int main(int argc, char* argv[]) {
    // ...
}
  • argc is how many arguments were given, including the program name.
  • argv is an array of C-strings holding each argument.

Print every argument

#include <iostream>

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

Running ./program hello 42 prints:

arg 0 = ./program
arg 1 = hello
arg 2 = 42

Read a numeric argument

Arguments are text, so convert with std::stoi:

#include <iostream>
#include <string>

int main(int argc, char* argv[]) {
    if (argc > 1) {
        int n = std::stoi(argv[1]);
        std::cout << "Double: " << n * 2 << "
";
    }
    return 0;
}

Guard the count

Check before indexing:

if (argc < 3) {
    std::cerr << "Usage: " << argv[0] << " name age
";
    return 1;
}

Never read past argc, and always validate the arguments you use.

TL;DR

  • argc counts arguments including the program name; argv holds them as C-strings.
  • argv[0] is the program's own name.
  • Convert text to numbers with std::stoi.
  • Always check argc before indexing argv.