测试 getopt
全局数据:
opterr: 默认值1 置0不输出错误信息(没有指定的参数、要求有value的参数没设置value)
optarg: char* 类型,指向key对应的value,遇未设置或开关参数为NULL
optind:下一个要处理的argv下标
getopt返回int表示找到的的key字母,如果没有在optstring中则返回?输出error信息。没有“-”开头则返回-1
测试结果:
在我系统下 optstring中:和::没有区别,都是必须指定value 而且都可以空格分隔或直接加在key后面(-a123 or -a 123)。需要key时char*不以“-”开头则返回-1,即 认为后面的都是arguments(并没有网上说的移动参数位置)
前面有没有+好像也没有区别
#include <iostream>
#include <string>
#include <map>
#include <unistd.h>
using namespace std;
int main(int argc, char* argv[]) {
int c;
map<string, string> opition;
string optstring("a:b:c::def:gh:i");
// optstring = "+a:b:c::def:gh:i";
opterr = 0;
cout << "optstring: " << optstring << endl;
while((c = getopt(argc, argv, optstring.c_str())) != -1) {
string key(1, static_cast<char>(c));
if(key == "?") {
cout << "error opition " << optind << endl;
}
string value;
if( optarg != NULL) {
value = optarg;
}
if( opition.find( key ) != opition.end() ) {
value += ":";
value += opition.find(key)->second;
}
opition[key] = value;
}
cout << "argument:" << endl;
for(int i=optind; i<argc; ++i) {
cout << argv[i] << endl;
}
cout << "opition:" << endl;
for(map<string, string>::iterator it = opition.begin(); it != opition.end(); ++it) {
cout << it->first << " " << it->second << endl;
}
return 0;
}
/*
./a.out -a df bf -b df
./a.out -a df -d -e1 -b df op
./a.out -a123 -d -e1 -b df op
./a.out -a123 -d -e 1 -b df op
./a.out -a123 -d -c 1 -e -b df op
./a.out -a123 -d -c1 -e -b df op
./a.out -a123 -d -c -e -b df op
./a.out -a -d -c 1 -e -b df op
./a.out -a -d -c 1 -e -b
./a.out -a adf abs -b
./a.out -k -a abc
./a.out -k -a abc -a fcd
./a.out -k -a abc -a fcd -b123 -c123
./a.out -k -a abc -a fcd -b123 -c
*/
</pre><pre>