您的位置:首页 > 运维架构

使用getopt_long解析程序长选项参数

2011-08-23 14:20 597 查看
写在前面:

对于可选参数一定要使用以下两种方法标明其值 –wValue  或--who==Value 而不能是 --who Value,

而对于必填参数则可以使用-lValue 或 --love Value或--love=Value,

这并不是bug.

//============================================================================

// Name        : TestOpt.cpp

// Author      : yangyh

// Version     :

// Copyright   : Your copyright notice

// Description : Hello World in C++, Ansi-style

//============================================================================

#include <iostream>

#include <getopt.h>

using namespace std;

int version;

struct option longopts[] = {

{ "version", no_argument, &version, 'v' },

{ "name", no_argument, NULL, 'n' },

{ "love", required_argument, NULL,'l' },

{ "who",optional_argument,NULL,'w'},

{ 0, 0, 0, 0 }

};

int main(int argc, char *argv[]) {

int c;

while ((c = getopt_long(argc, argv, "vl:w::", longopts, NULL)) != -1) {

switch (c) {

case 'l':

printf("love = %s!\n", optarg);

break;

case 0:

//

printf("getopt_long()设置变量 : version = %c\n", version);

break;

case 'v':

printf("version..\n");

break;


      case 'w':

printf("who = %s\n",optarg);

break;

}

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: