getopt how to set a default value

user9314692
#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?

melpomene

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related