C++でコマンドライン引数のパース
ヘッダ1つで使えるezOptionParserというのを
このあいだ使ったので、自分が使いそうな機能だけ抜き出して、メモ。
ヘッダ1つで使えるのは便利だ。
ソース
#include "ezOptionParser.hpp" #include <string> #include <iostream> using namespace std; void print_usage(ez::ezOptionParser& opt){ string s; opt.getUsage(s); cout << s; } int main(int argc, const char *argv[]){ // setting and parse ez::ezOptionParser opt; opt.overview = "sample of ezOptionParser"; opt.syntax = "a.out [options]"; opt.example = "a.out --str \"hoge\" --int 1,2\n"; opt.footer = "\nThis program has no footer\n"; opt.add("", false, 0, 0, "show usage", "-h", "--help"); opt.add("", true, 1, 0, "sample string", "--str"); opt.add("", true, 2, ',', "sample int", "--int"); opt.parse(argc, argv); // check if there is help if(opt.isSet("-h")){ print_usage(opt); return 1; } // check validity(required options) vector<string> badOpts; if(!opt.gotRequired(badOpts)){ cerr << "Error: missing following options" << endl; for (size_t i = 0; i < badOpts.size(); i++) { cerr << badOpts[i] << endl; } print_usage(opt); return 1; } // check validity(number of arguments) if(!opt.gotExpected(badOpts)){ cerr << "Error: got unexpected number of arguments" << endl; for (size_t i = 0; i < badOpts.size(); i++) { cerr << badOpts[i] << endl; } print_usage(opt); return 1; } // get values vector<int> is; opt.get("--int")->getInts(is); for (size_t i = 0; i < is.size(); i++) { cout << "is[" << i << "]=" << is[i] << endl; } string s; opt.get("--str")->getString(s); cout << "s=" << s << endl; return 0; }
ヘルプ出力
$ ./a.out -h sample of ezOptionParser USAGE: a.out [options] OPTIONS: -h, --help show usage --int ARG1[,ARGn] sample int --str ARG sample string EXAMPLES: a.out --str "hoge" --int 1,2 This program has no footer