C 为同一选项获取多个值
我有一个这样的程序:C 为同一选项获取多个值,c,getopt,C,Getopt,我有一个这样的程序: ./server 其中有以下用法: Usage : -p Port to use (4242 by default) -x Map width (20) -y Map height (20) -n Team name (name_team1 name_team2) -c Players per team -t Delay 我能够用以下代码解析所有选项: int parse_cmd(int argc, char **argv, t_args *a) {
./server
其中有以下用法:
Usage :
-p Port to use (4242 by default)
-x Map width (20)
-y Map height (20)
-n Team name (name_team1 name_team2)
-c Players per team
-t Delay
我能够用以下代码解析所有选项:
int parse_cmd(int argc, char **argv, t_args *a)
{
char ch;
if (argv[1] && argv[1][0] != '-')
usage();
while ((ch = getopt(argc, argv, "p:x:y:n:c:t:")) != -1)
{
if (ch == 'p')
a->port = atoi(optarg);
else if (ch == 'x')
a->x = atoi(optarg);
else if (ch == 'y')
a->y = atoi(optarg);
else if (ch == 'n')
a->teams = name_teams(optarg);
else if (ch == 'c')
a->size = atoi(optarg);
else if (ch == 't')
a->delay = atoi(optarg);
else
usage();
}
if (check_values(a) == FALSE)
return (FALSE);
return (TRUE);
}
但问题是,对于-n
选项,我必须获得如下团队名称:
./server -n team1 team2 team2
我就是不能改变现状
显然,我能做到:
./server -n "team1 team2 team3"
分析团队,但这是为我的公司,他们不想在团队名称周围加引号,不要问我为什么
在不使用shell中的引号的情况下,如何获取所有团队名称方面有什么帮助吗?我认为您有三种不同的可能性:
./server -n team1 -n team2 -n team3
./server -n team1,team2,team3
我认为你有三种不同的可能性:
./server -n team1 -n team2 -n team3
./server -n team1,team2,team3
使用
else if(ch='n')
分支中的getopt
解析所有团队,直到下一个选项出现。使用else if(ch='n')
分支中的getopt
解析所有团队,直到下一个选项出现。您也可以使用optand
<代码>选项跟踪遇到的选项数量optind
指向argv[]
中getopt()遇到的下一个索引
因此,您可以在argv
中查找是否有团队。但要使其起作用,您应该在optstring中省略“:”,就像在下一个片段”中一样,p:x:y:nc:t:“
或在循环中使用optint之前减小其值
这只是一个确定循环是否必须继续的简单函数
int
is_team ( const char* team ) {
if ( team == NULL)
return 0;
else if ( team[0] == '-' ) /*new argument*/
return 0;
else
return 1;
}
这就是当遇到“n”选项时所做的。您也可以在optstring中使用冒号,但是遇到选项也会被计数,然后i=optind-1
可能也会起作用
case 'n':
{ /*note this scope is significant*/
int i;
for ( i = optind ; is_team(argv[i]); ++i ) {
printf ( "team = %s\n", argv[i]);
//argument = ++*optarg;
}
}
break;
我希望这有帮助。您也可以使用选项和
<代码>选项
跟踪遇到的选项数量optind
指向argv[]
中getopt()遇到的下一个索引
因此,您可以在argv
中查找是否有团队。但要使其起作用,您应该在optstring中省略“:”,就像在下一个片段”中一样,p:x:y:nc:t:“
或在循环中使用optint之前减小其值
这只是一个确定循环是否必须继续的简单函数
int
is_team ( const char* team ) {
if ( team == NULL)
return 0;
else if ( team[0] == '-' ) /*new argument*/
return 0;
else
return 1;
}
这就是当遇到“n”选项时所做的。您也可以在optstring中使用冒号,但是遇到选项也会被计数,然后i=optind-1
可能也会起作用
case 'n':
{ /*note this scope is significant*/
int i;
for ( i = optind ; is_team(argv[i]); ++i ) {
printf ( "team = %s\n", argv[i]);
//argument = ++*optarg;
}
}
break;
我希望这能有所帮助。这就成功了!谢谢成功了!谢谢