GTK+ IOStream  Beta
<< GTK+ >> add C++ IOStream operators to GTK+. Now with extra abilities ... like network serialisation
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
OptionParser.H
Go to the documentation of this file.
1 /* Copyright 2000-2013 Matt Flax <flatmax@flatmax.org>
2  This file is part of GTK+ IOStream class set
3 
4  GTK+ IOStream is free software; you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation; either version 2 of the License, or
7  (at your option) any later version.
8 
9  GTK+ IOStream is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  GNU General Public License for more details.
13 
14  You have received a copy of the GNU General Public License
15  along with GTK+ IOStream
16  */
17 #ifndef OPTIONPARSER_H_
18 #define OPTIONPARSER_H_
19 
20 #include <sstream>
21 #include <string>
22 using namespace std;
23 #include <string.h>
24 
31 class OptionParser {
32 public:
42  template<typename TYPE>
43  int getArg(string key, int argc, char *argv[], TYPE &ret, int i) {
44  string args;
45  int rv=getArgString(key, argc, argv, args, i);
46  stringstream arg;
47  arg<<args;
48  arg>>ret;
49  return rv;
50  }
51 
60  int getArgString(string key, int argc, char *argv[], string &ret, int i) {
61  int loc=i;
62  do {
63  // if found, then break, with loc==i.
64  int startIndex=0; // strip any leading '-'
65  while (argv[i][startIndex]=='-') startIndex++;
66  if ((startIndex!=0) & (strncmp(key.c_str(), string(&argv[i][startIndex]).substr(0,key.length()).c_str(), key.length())==0)) { // we have a match !
67  // find if the key is in the first position
68  loc=i;
69  loc++;
70  string arg(&argv[i][startIndex]);
71  if ((key.length()==arg.length()) & (i+1<argc)) { // argument is of the form : -count 10, so get the next arg.
72  if (argv[i+1][0]!='-') // guard against the -h -v case
73  ret=argv[++i];
74  } else { // argument is for the form : --count=10, so strip the initial part
75  istringstream input(arg);
76  input.ignore(arg.length(),'=');
77  unsigned int length=input.tellg();
78  if (--length==key.length()) // ensure that we havn't matched -n for -net
79  input>>ret;
80  }
81  break;
82  }
83  } while (++i<argc);
84  return loc;
85  }
86 };
87 
88 #endif // OPTIONPARSER_H_