Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C getopt_long问题_C_Command Line Arguments_Getopt Long - Fatal编程技术网

C getopt_long问题

C getopt_long问题,c,command-line-arguments,getopt-long,C,Command Line Arguments,Getopt Long,我在解析我正在编写的程序中的参数时遇到问题,代码如下: void parse_args(int argc, char** argv) { char ch; int index = 0; struct option options[] = { { "help", no_argument, NULL, 'h' }, { "port", required_argument, NULL, 'p' },

我在解析我正在编写的程序中的参数时遇到问题,代码如下:

void parse_args(int argc, char** argv)
{
    char ch;
    int index = 0;

    struct option options[] = {       
        { "help", no_argument, NULL, 'h'   },      
        { "port", required_argument, NULL, 'p'  },      
        { "stop", no_argument, NULL, 's' },         
        { 0,    0,    0,    0   }       
    };

    while ((ch = getopt_long(argc, argv, "hp:s", options, &index)) != -1) {
        switch (ch) {
            case 'h':   
                printf("Option h, or --help.\n");
                break;
            case 's':
                printf("Option s, or --stop.\n");

                break;
            case 'p':
                printf("Option p, or --port.\n");
                if (optarg != NULL)
                    printf("the port is %s\n", optarg);
                break;
            case '?':
                printf("I don't understand this option!!!\n");

            case -1:  
                break;
            default:
                printf("Help will be printed very soon -:)\n");
        }
    }
}
当我运行我的程序时,我得到了一些奇怪的输出:

./Server -p 80
Option p, or --port.
the port is 80

./Server -po 80
Option p, or --port.
the port is o

./Server -por 80
Option p, or --port.
the port is or

./Server -hoho
Option h, or --help.
Server: invalid option -- o
I don't understand this option!!!

我认为这种混乱源于对long get opt的误解。本质上,它只在使用
--
表单时进行部分字符串匹配。当您仅使用
-
时,它将退回到标准解析,因此
-por 80
匹配为
-p或80
(如中所示,选项为
-p
,参数为
)。用
--po
--por
试试同样的方法。至于帮助,请尝试
--he
--hel

为什么奇怪?你期待什么?最后三次执行输出很奇怪!!!不,不是。您传递
-p
,它将下一个事物(
o
)解释为计数,并忽略
80
p
应该在
o
r
之后。在第四轮中,每个字母只算一次。它接受折叠在一起的单字母选项,就像在Unix中键入
ls-ltr
时一样。你不知道吗?用
退出,这不像你是这里任何人的老板。至于getopt(),它是有效的,但它的行为不像你认为应该的那样。欢迎来到您的编码生活。如果你想改变它,你必须自己去做。或者,您将不得不接受另一种解析输入的方式。不管怎样,你都必须验证你的输入。相信我。谢谢,这更清楚,所以如果我知道处理用户输入的唯一安全方法是使用strcmp()之类的东西来验证用户字符串?@funnyCoder还有另一个调用
getopt\u long\u only
。检查一下谢谢大家,你们的帮助很棒:)