如果用户选择 -p
而不是 -pc
,我必须打印两个不同的输出。一个有论据,另一个没有论据。如果我尝试:
while( (arg = getopt_long(argc, argv, "p:")) != -1 )
{
switch (arg)
{
case 'p':
p = optarg;
if (p=='')
sflag = true;
if (p=='c')
oflag = true;
break;
}
然后 -pc
可以工作,但是如果我尝试 -p
,我会收到一条错误消息,提示需要一个参数。如何处理 optional 参数?
最佳答案
你在使用 GNU 吗?如果是这样,你很幸运。来自docs :
The options argument is a string that specifies the option characters that are valid for this program. An option character in this string can be followed by a colon (
:
) to indicate that it takes a required argument. If an option character is followed by two colons (::
), its argument is optional; this is a GNU extension.
因此,您需要:
while( (arg = getopt_long(argc, argv, "p::")) != -1 )
关于c++ - 我可以在 C++ 中使用 getopt 来读取带参数和不带参数的字符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35975090/