The main function receives the command-line arguments through two parameters. The first one is the count of them, and the second one is the array of the strings. Reading them is easy, and the work is in turning the raw strings into the values that your program actually wants.
The previous lesson in this module covered "What Do Binary Files Change About IO?", and this lesson is the last one in the Files and Practical IO module.
The two parameters
#include <iostream>
int main(int argc, char* argv[]) {
std::cout << "argc: " << argc << '\n';
for (int i = 0; i < argc; ++i) {
std::cout << "argv[" << i << "]: " << argv[i] << '\n';
}
return 0;
}And running the program with no arguments gives this.
argc: 1
argv[0]: ./69-a.binSo the first element of the array is always the name of the program, and the rest are the arguments that the user gave. And the standard also allows a third parameter, the envp, that holds the environment.
Parsing options by hand
The usual approach is a loop over the arguments, recognising the ones that you know and collecting the rest.
#include <iostream>
#include <string>
int main(int argc, char* argv[]) {
int count = 10;
bool verbose = false;
std::string path = "members.txt";
for (int i = 1; i < argc; ++i) {
std::string argument = argv[i];
if (argument == "--verbose" || argument == "-v") {
verbose = true;
} else if (argument == "--count") {
if (i + 1 >= argc) {
std::cerr << "--count needs a value\n";
return 1;
}
count = std::stoi(argv[++i]);
} else if (argument == "--path") {
if (i + 1 >= argc) {
std::cerr << "--path needs a value\n";
return 1;
}
path = argv[++i];
} else {
std::cerr << "unknown option: " << argument << '\n';
return 1;
}
}
std::cout << "count: " << count << '\n';
std::cout << "path: " << path << '\n';
std::cout << "verbose: " << std::boolalpha << verbose << '\n';
return 0;
}And running it with no arguments gives the defaults.
count: 10
path: members.txt
verbose: falseA cleaner argument parser
Once there are more than two or three options, a small parser with a helper function keeps the main loop readable.
#include <iostream>
#include <stdexcept>
#include <string>
struct Options {
int count = 10;
bool verbose = false;
std::string path = "members.txt";
};
Options parse(int argc, char* argv[]) {
Options options;
for (int i = 1; i < argc; ++i) {
std::string argument = argv[i];
if (argument == "-v" || argument == "--verbose") {
options.verbose = true;
} else if (argument == "--count" || argument == "-c") {
if (i + 1 >= argc) {
throw std::invalid_argument("--count needs a value");
}
options.count = std::stoi(argv[++i]);
} else if (argument == "--path" || argument == "-p") {
if (i + 1 >= argc) {
throw std::invalid_argument("--path needs a value");
}
options.path = argv[++i];
} else {
throw std::invalid_argument("unknown option: " + argument);
}
}
return options;
}
int main(int argc, char* argv[]) {
try {
Options options = parse(argc, argv);
std::cout << "count: " << options.count << '\n';
std::cout << "path: " << options.path << '\n';
std::cout << "verbose: " << std::boolalpha << options.verbose << '\n';
} catch (const std::exception& error) {
std::cerr << "error: " << error.what() << '\n';
return 1;
}
return 0;
}Usage text and exit codes
The convention is to print the usage to the standard error and to exit with a non-zero status when the arguments are wrong.
#include <iostream>
#include <string>
void print_usage(const char* program) {
std::cout << "usage: " << program << " [--count N] [--path FILE] [--verbose]\n";
std::cout << " --count N number of records to process\n";
std::cout << " --path FILE file to read\n";
std::cout << " --verbose print more detail\n";
}
int main(int argc, char* argv[]) {
if (argc > 1 && std::string(argv[1]) == "--help") {
print_usage(argv[0]);
return 0;
}
if (argc < 2) {
print_usage(argv[0]);
return 0;
}
std::cout << "processing " << argv[1] << '\n';
return 0;
}And the output when the program is run with no arguments is this.
usage: ./69-d.bin [--count N] [--path FILE] [--verbose]
--count N number of records to process
--path FILE file to read
--verbose print more detailConverting arguments safely
The safer conversion checks that the whole string was consumed.
#include <charconv>
#include <iostream>
#include <optional>
#include <string>
std::optional<int> to_int(const std::string& text) {
int value = 0;
const char* first = text.data();
const char* last = text.data() + text.size();
const auto result = std::from_chars(first, last, value);
if (result.ec != std::errc{} || result.ptr != last) {
return std::nullopt;
}
return value;
}
std::string describe(const std::optional<int>& value) {
if (!value.has_value()) {
return "rejected";
}
return std::to_string(*value);
}
int main(int argc, char* argv[]) {
const std::string text = (argc >= 2) ? argv[1] : "12";
std::cout << "text '" << text << "' -> " << describe(to_int(text)) << '\n';
std::cout << "text '12x' -> " << describe(to_int("12x")) << '\n';
std::cout << "text '' -> " << describe(to_int("")) << '\n';
return 0;
}Quick reference
- The
argcis the number of the arguments and theargvis the array of them. - The
argv[0]is the name of the program, and the rest start at the index one. - You always check that an option that needs a value has one before you read it.
- You return a non-zero status when the arguments are wrong.
- You print the usage when the help is asked for, and usually to the standard error.
- You use the
std::from_charsto convert the text safely, and you check that the whole text was consumed.
Try it yourself: write a program that takes a count and a path on the command line, and that prints the usage and exits with a status of one when they are missing. Then convert the count with the safe helper and reject the value that has the trailing characters in it. Finally, add a verbose flag and check that it works with both the short and the long form.