-
Notifications
You must be signed in to change notification settings - Fork 0
Parsing common data types
Often a command line argument or option value needs to be converted into a specific data type inside your application code. Examples include converting an argument into an integer, an enum or a floating point number. You can, of course, relatively easily perform such a conversion yourself using whatever facilities you prefer. However, doing it in C++ safely and correctly is often unnecessarily hard. To help with this Argument provides a few type parsers - utility functions or classes to simplify such common tasks.
If you are not using single-header (or module) distribution these parsers are available in <argum/type-parsers.h>
header.
Function template parseIntegral<Type>
allows you to convert a string_view
/wstring_view
into any integral type. The format it accepts is as follows
- Any number of spaces followed by
- A number recognized by the family of
strtoX
standard functions (see here and here). The number must fit into the destination type. - Any number of spaces
The second argument to parseIntegral
is "base" which operates exactly like the "base" argument of strtoX
family of functions. By default it is 0
- meaning "guess based on prefix".
If the format cannot be parsed the function throws Parser::ValidationError
. Otherwise it returns the parsed integral.
Here is an example:
unsigned short aNumber;
...
parser.add(
Positional("number").
help("a number").
handler([&](const std::string_view & value) {
aNumber = parseIntegral<unsigned short>(value);
}));
Very similar to the above there is also parseFloatingPoint<Type>
that can parse float
, double
or long double
. It operates almost identically except the parsing format is the one of strtof family of functions.
Very often an argument or option value must be a choice between different fixed options. The choices might map to some actual enum
in application code or just be some fixed allowed values. To complicate matters, sometimes multiple command line choices (or alternative spellings) must map to a single entry in program code.
To deal with all that Argum provides ChoiceParser
(and WChoiceParser
) class.
- Home
-
Usage Guide
Basics
Error Handling
Thread Safety
Adding Help
Defining options
Positional arguments
Reporting errors from handlers
Parsing common data types
Validation
Depending on order
Subcommands
Response files
Partial Parsing -
Advanced
Syntax Description
Customizing syntax
Customizing usage and help
Localization