argparse/samples/positional_argument.cpp
cobyj33 1a7a1dfd43 Change parse_args examples to catch const std::exception instead of std::runtime_error
parse_args can throw exceptions that are not based on std::runtime_error, and the
error message should show on all errors.
2023-10-25 20:33:24 -05:00

31 lines
754 B
C++

// SPDX-License-Identifier: MIT
#include <argparse/argparse.hpp>
int main(int argc, char *argv[]) {
argparse::ArgumentParser program("main");
program.add_argument("square")
.help("display the square of a given number")
.scan<'i', int>();
program.add_argument("--verbose").default_value(false).implicit_value(true);
try {
program.parse_args(argc, argv);
} catch (const std::exception &err) {
std::cerr << err.what() << std::endl;
std::cerr << program;
return 1;
}
int input = program.get<int>("square");
if (program["--verbose"] == true) {
std::cout << "The square of " << input << " is " << (input * input)
<< std::endl;
} else {
std::cout << (input * input) << std::endl;
}
}