1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| /*
如果解析不存在的参数,会报段错误,最好加默认值
TODO:添加子命令,类似 git log、git status 这样的 */
#include "cmdline.h"
#include <stdio.h> #include <iostream> using namespace std;
bool g_bPrint = false;
// 有些帮助信息过多,使用函数组装 char* getHelp(int type) { static char info[256] = {0}; if (type == 't') { sprintf(info, " test type \n \ autotest - for auto test\n \ dualtest - for dual version test\n \ more comming up..."); }
return info; }
int main(int argc, char *argv[]) { cmdline::parser theArgs; // 一般形式:长命令名、短命令名(如不支持短命令填'\0'),描述,是否必填,默认值 // 如果为必填,则在运行时必须带该参数,否则解析失败 theArgs.add<string>("test", 't', getHelp('t'), false, "auto"); theArgs.add<string>("host", 'h', "host name", false, ""); theArgs.add<int>("rate", 'r', "rate number", false, 80, cmdline::range(1, 65535)); // 带默认值、范围的
// bool 型,与上述不同,后判断有无该参数 theArgs.add("print", 'p', "show message"); // 需要判断是否存在,存在则置标志为true //theArgs.add("help", 0, "print this message1111");
//theArgs.footer("filename ..."); //theArgs.set_program_name("mytool"); theArgs.set_program_name(argv[0]); // 调整位置,让cmdline误以为第二个参数才是命令 //theArgs.parse_check(argc-1, &argv[1]);
try{ printf("test type: %s\n", theArgs.get<string>("test").c_str()); } catch(const std::exception &e){} try{ printf("bad: %s\n", theArgs.get<string>("bad").c_str()); // 不存在的参数 } catch(const std::exception &e){ printf("param [bad] not exist...\n"); } try{ printf("host: %s\n", theArgs.get<string>("host").c_str()); } catch(const std::exception &e){} try{ printf("rate: %d\n", theArgs.get<int>("rate")); } catch(const std::exception &e){} try{ printf("rest args: \n"); for (int i = 0; i < (int)theArgs.rest().size(); i++) { //cout << theArgs.rest()[i] << endl; printf("%s\n", theArgs.rest()[i].c_str()); } } catch(const std::exception &e){}
// 此法不能判断不存在的参数 // if (theArgs.exist("type")) // { // printf("type111: %d\n", theArgs.get<string>("type").c_str()); // } // if (theArgs.exist("rate")) // 非bool类型,似乎也不能如此判断 { printf("rate111: %d\n", theArgs.get<int>("rate")); }
if (theArgs.exist("print")) { g_bPrint = false; } return 0; }
|