getopt how to set a default value

主宰稳场 提交于 2019-12-11 04:08:39

问题


#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>


int main(int argc, char **argv) {
    int o;
    int w = 10;

    while ((o = getopt(argc, argv, "w")) != -1) {
        switch (o) {
            case 'w' :
                w = atoi(optarg);
                break;



        }

    }
    printf("%d\n", w);
}

Basically, I want -w to have if nothing is inputted.

Consider these use cases

$ gcc -Wall fileabove.c
$ ./a.out 
10
$ ./a.out -w
10
$ ./a.out -w14
14

I can't get the second one to work. Is there any way I can play around with getopt to get the expected result?


回答1:


Assuming you're using GNU getopt, the following should work:

    while ((o = getopt(argc, argv, "w::")) != -1) {
        switch (o) {
            case 'w' :
                if (optarg) {
                    w = atoi(optarg);
                }
                break;

A following : marks the option as requiring an argument. A double : makes the argument optional (this is a GNU extension). If there is no argument, optarg is NULL.



来源:https://stackoverflow.com/questions/49021769/getopt-how-to-set-a-default-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!