我需要像这样调用我的程序:
./program hello -r foo bar
Run Code Online (Sandbox Code Playgroud)
我从argv [1]中打招呼,但我在价值栏上遇到麻烦,我还应该将"r:"更改为其他内容吗?
while((c = getopt(argc, argv, "r:")) != -1){
switch(i){
...
case 'r':
var_foo = optarg;
//shell like argument shift here?
var_bar = optarg;
break;
...}
Run Code Online (Sandbox Code Playgroud)
我知道我可以通过argv来做到这一点,但有没有办法用getopt与bash类似的方式来做到这一点?
谢谢.
bar在眼中并不是一个选择论证getopt.相反,GNU getopt 重新排列位置参数,以便在处理结束时,您已经argv[3]"hello"并且argv[4]是"bar".基本上,当你完成getopting时,你仍然有位置参数[optind, argc)来处理:
int main(int argc, char * argv[])
{
{
int c;
while ((c = getopt(argc, argv, ...)) != -1) { /* ... */ }
}
for (int i = optind; i != argc; ++i)
{
// have positional argument argv[i]
}
}
Run Code Online (Sandbox Code Playgroud)