1#ifndef COMMAND_LINE_ARGS_HPP
2#define COMMAND_LINE_ARGS_HPP
13 std::map<std::string, std::string> args;
14 std::vector<std::string> positionalArgs;
15 std::vector<std::string> validFlags;
18 CommandLineArgs(
int argc,
char* argv[],
const std::vector<std::string>& allowedFlags = {})
19 : validFlags(allowedFlags)
21 parseArgs(argc, argv);
24 std::string
get(
const std::string& flag,
const std::string& defaultValue =
"")
const
26 auto it = args.find(flag);
34 bool hasFlag(
const std::string& flag)
const
36 return args.find(flag) != args.end();
41 return positionalArgs;
46 std::cerr <<
"Usage: " << programName <<
" [options] [positional arguments]\n";
47 if (!validFlags.empty())
49 std::cerr <<
"Valid options:\n";
50 for (
const auto& flag : validFlags)
52 std::cerr <<
" " << flag <<
"\n";
58 void parseArgs(
int argc,
char* argv[])
60 for (
int i = 1; i < argc; ++i)
62 std::string arg = argv[i];
66 std::string flag = arg;
70 if (i + 1 < argc && argv[i + 1][0] !=
'-')
76 if (!validFlags.empty() && std::find(validFlags.begin(), validFlags.end(), flag) == validFlags.end())
78 throw std::invalid_argument(
"Invalid flag: " + flag);
85 positionalArgs.push_back(arg);
void printUsage(const std::string &programName) const
Definition cmd-line-args.hpp:44
bool hasFlag(const std::string &flag) const
Definition cmd-line-args.hpp:34
CommandLineArgs(int argc, char *argv[], const std::vector< std::string > &allowedFlags={})
Definition cmd-line-args.hpp:18
const std::vector< std::string > & getPositionalArgs() const
Definition cmd-line-args.hpp:39
std::string get(const std::string &flag, const std::string &defaultValue="") const
Definition cmd-line-args.hpp:24