Tori's Corner

Project Title

C++ Class for Parsing Command-Line Arguments

This project is available on Github.
This project has been discontinued and will not receive updates.

What is this?

Argument Parser is a development tool for C++ CLI programs. It accepts an std::vector of ArgumentTemplate structures that dictate valid arguments and flags, as well as the standard argc integer and argv array.

Usage

To get started with Argument Parser, simply drop the files into your project and add them to any build chain setup. Including the header file will then allow you to use the class and its features. To instantiate the class, you need access to the argc and argv variables provided by the operating system, as well as an std::vector of ArgumentTemplate structures.

Argument Templates

The ArgumentTemplate is a simple structure that contains information on a parameter or flag. The parser class will use these to find different arguments provided by the user. It contains the following fields:

  1. argumentType (uin8_t) -- The type of the argument. A combination of ARG_REQUIRED, ARG_OPTIONAL, ARG_POSITIONAL and ARG_IMPLIED.
  2. flag (std::string) -- Only used if the template does not have the property ARG_POSITIONAL and ARG_REQUIRED. Dictates the flag that must be typed for the argument to be recognised (such as -h).
  3. name (std::string) -- Determines the name of the argument that should be used to find it after parsing. Should be unique.

Positional arguments (ARG_POSITIONAL) are parsed in the order they are added to the std::vector. If an argument is marked as requried (ARG_REQUIRED) must be present, or else the parser will throw an error. Implied arguments (ARG_IMPLIED) do not require a value to be specified by the user, instead they require a flag to be present (for example -h to display help).

Parsing the Arguments

When the parser has been instantiated, the next step is to parse the arguments using the ArgumentParser.parseArguments(); function. This function returns true if the arguments were successfully parsed, or false if there was an error. The function expects an empty std::vector of Argument structures to be passed as an argument, which will be populated by the function.

When this has finished, you will be left with an std::vector of Argument structures that contain the information on command-line arguments. The ArgumentParser.argumentExists() and ArgumentParser.getArgByName() functions can then be used to extract specific arguments from the vector for use in the program. At this point, it is also safe to delete the parser instance.