The Lean Mean C++ Option Parser
src/example.cpp
Go to the documentation of this file.
00001 /* Written 2012 by Matthias S. Benkmann
00002  *
00003  * The author hereby waives all copyright and related rights to the contents
00004  * of this example file (example.cpp) to the extent possible under the law.
00005  */
00006 
00014 #include <iostream>
00015 #include <string>
00016 #include <vector>
00017 #include "optionparser.h"
00018 
00019 enum  optionIndex { UNKNOWN, HELP, PLUS };
00020 const option::Descriptor usage[] =
00021 {
00022  {UNKNOWN, 0, "", "",option::Arg::None, "USAGE: example [options]\n\n"
00023                                         "Options:" },
00024  {HELP, 0,"", "help",option::Arg::None, "  --help  \tPrint usage and exit." },
00025  {PLUS, 0,"p","plus",option::Arg::None, "  --plus, -p  \tIncrement count." },
00026  {UNKNOWN, 0, "", "",option::Arg::None, "\nExamples:\n"
00027                                "  example --unknown -- --this_is_no_option\n"
00028                                "  example -unk --plus -ppp file1 file2\n" },
00029  {0,0,0,0,0,0}
00030 };
00031 
00032 int main(int argc, char* argv[])
00033 {
00034   argc-=(argc>0); argv+=(argc>0); // skip program name argv[0] if present
00035   option::Stats  stats(usage, argc, argv);
00036   std::vector<option::Option> options(stats.options_max);
00037   std::vector<option::Option> buffer(stats.buffer_max);
00038   option::Parser parse(usage, argc, argv, &options[0], &buffer[0]);
00039 
00040   if (parse.error())
00041     return 1;
00042 
00043   if (options[HELP] || argc == 0) {
00044     option::printUsage(std::cout, usage);
00045     return 0;
00046   }
00047 
00048   std::cout << "--plus count: " <<
00049       options[PLUS].count() << "\n";
00050 
00051   for (option::Option* opt = options[UNKNOWN]; opt; opt = opt->next())
00052     std::cout << "Unknown option: " << std::string(opt->name,opt->namelen) << "\n";
00053 
00054   for (int i = 0; i < parse.nonOptionsCount(); ++i)
00055     std::cout << "Non-option #" << i << ": " << parse.nonOption(i) << "\n";
00056 }
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator