Loading lessons...
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[]) {
// ...
}
argcis how many arguments were given, including the program name.argvis 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
argccounts arguments including the program name;argvholds them as C-strings.argv[0]is the program's own name.- Convert text to numbers with
std::stoi. - Always check
argcbefore indexingargv.