The Lean Mean C++ Option Parser
example.cpp
Go to the documentation of this file.
1 /* Written 2012 by Matthias S. Benkmann
2  *
3  * The author hereby waives all copyright and related rights to the contents
4  * of this example file (example.cpp) to the extent possible under the law.
5  */
6 
14 #include <iostream>
15 #include <string>
16 #include <vector>
17 #include "optionparser.h"
18 
19 enum optionIndex { UNKNOWN, HELP, PLUS };
20 const option::Descriptor usage[] =
21 {
22  {UNKNOWN, 0, "", "",option::Arg::None, "USAGE: example [options]\n\n"
23  "Options:" },
24  {HELP, 0,"", "help",option::Arg::None, " --help \tPrint usage and exit." },
25  {PLUS, 0,"p","plus",option::Arg::None, " --plus, -p \tIncrement count." },
26  {UNKNOWN, 0, "", "",option::Arg::None, "\nExamples:\n"
27  " example --unknown -- --this_is_no_option\n"
28  " example -unk --plus -ppp file1 file2\n" },
29  {0,0,0,0,0,0}
30 };
31 
32 int main(int argc, char* argv[])
33 {
34  argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present
35  option::Stats stats(usage, argc, argv);
36  std::vector<option::Option> options(stats.options_max);
37  std::vector<option::Option> buffer(stats.buffer_max);
38  option::Parser parse(usage, argc, argv, &options[0], &buffer[0]);
39 
40  if (parse.error())
41  return 1;
42 
43  if (options[HELP] || argc == 0) {
44  option::printUsage(std::cout, usage);
45  return 0;
46  }
47 
48  std::cout << "--plus count: " <<
49  options[PLUS].count() << "\n";
50 
51  for (option::Option* opt = options[UNKNOWN]; opt; opt = opt->next())
52  std::cout << "Unknown option: " << std::string(opt->name,opt->namelen) << "\n";
53 
54  for (int i = 0; i < parse.nonOptionsCount(); ++i)
55  std::cout << "Non-option #" << i << ": " << parse.nonOption(i) << "\n";
56 }
Determines the minimum lengths of the buffer and options arrays used for Parser.
Definition: optionparser.h:950
This is the only file required to use The Lean Mean C++ Option Parser. Just #include it and you&#39;re se...
static ArgStatus None(const Option &, bool)
For options that don&#39;t take an argument: Returns ARG_NONE.
Definition: optionparser.h:926
A parsed option from the command line together with its argument if it has one.
Definition: optionparser.h:442
Option * next()
Returns a pointer to the next element of the linked list or NULL if called on last().
Definition: optionparser.h:695
Checks argument vectors for validity and parses them into data structures that are easier to work wit...
Describes an option, its help text (usage) and how it should be parsed.
Definition: optionparser.h:315
void printUsage(OStream &prn, const Descriptor usage[], int width=80, int last_column_min_percent=50, int last_column_own_line_max_percent=75)
Outputs a nicely formatted usage string with support for multi-column formatting and line-wrapping...