C开关问题
我是编程新手,我想添加一个开关,该开关将接受 -aa
、-aaa
、-aaaaaa
等选项情况code> 等,除了 case a
之外,这三种情况中的每一种都可以提供单一功能?
我在想……
int option = getopt (argc, argv, "abcd");
switch(option){
case 'a': BLAH = TRUE;
break;
case 'b': FOO = TRUE;
break;
case 'c': BAR = TRUE;
break;
case 'd': BAZ = TRUE;
break;
}
for(int i = 1; i<argc; i++){
if ( argv[i][0] == '-' && argv[i][1] == 'a' && argv[i][i+2] == 'a' )
myOption =TRUE;
}
但这行得通吗? 感谢您的阅读。
I'm new to programming and I would like to add to a switch that would take in option cases such as -aa
, -aaa
, -aaaaaa
etc where each of these three cases could serve a singular function in addition to case a
?
I was thinking...
int option = getopt (argc, argv, "abcd");
switch(option){
case 'a': BLAH = TRUE;
break;
case 'b': FOO = TRUE;
break;
case 'c': BAR = TRUE;
break;
case 'd': BAZ = TRUE;
break;
}
for(int i = 1; i<argc; i++){
if ( argv[i][0] == '-' && argv[i][1] == 'a' && argv[i][i+2] == 'a' )
myOption =TRUE;
}
But would this work?
Thanks for reading.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
getopt_long(3)
函数为许多程序提供命令行解析,通常使用如下调用:您可以使用
getopt_long(3)
扫描一组输入来查找映射到单个短选项(<代码>a或B
)。但如果您更具体地了解您想要完成的任务,可能会有更好的机制可用。
The
getopt_long(3)
function provides command-line parsing to many programs, typically with invocations like this:You might be able to use
getopt_long(3)
to scan an array of inputs to look for multiple inputs (thinkadd
,binary
, etc. from thelong_options[]
) that map to a single short option (a
orB
).But if you are more specific about what you're trying to accomplish, there might be a better mechanism available.
不,这可能行不通。 C 中的最佳方法(假设您使用 Linux)是使用一些 getopt GNU C 库提供的函数。如果您只需要处理一两个长选项,您还可以使用
if..else if
和strcmp()
。上次我检查了 BSD 的 libc 也存在类似的功能(不过可能有点不同)。
No, this probably would not work. The best way in C (assuming you use Linux) is to use some of the getopt functions that the GNU C library provides. You could also use
if..else if
andstrcmp()
if you just need to process one or two long options.Last time I checked similar features exist for BSD's libc as well (might be a bit different, though).
'aaa'
不是整数,不是字符,也不是 C 语言中的任何类型。传递给 switch 语句的表达式应返回一个整数。所以,switch 语句会在那里抱怨。对于非整数比较(例如您列出的比较),使用 if-else 应该很好。
'aaa'
is not integer, not char, and, not any type in the C language. The expression passed to switch statement should return an integer. So, switch statement is going to complain there.For non integer comparisons such as the ones you have listed out, using if-else should be good.