Search code examples
c++argumentscommand-line-argumentsgetoptgetopt-long

Print default argument when using getopt in C++


static struct option long_options[] =
{
     {"r",   required_argument,  0, 'r'},
     {"help",        no_argument,        0, 'h'},
     {0, 0, 0, 0}
};


int option_index = 0;
char c;
while((c = getopt_long(argc, argv, "r:h", long_options, &option_index)) != -1)
{
    switch(c)
    {
        case 'r':
            break;
        case 'h':
            return EXIT_SUCCESS;
    }
}

How do I make h the default argument, so if this program is run without any arguments, it will be as if it was run with -h?


Solution

  • Maybe try something like this:

    static struct option long_options[] =
    {
         {"r",    required_argument,  0, 'r'},
         {"help", no_argument,        0, 'h'},
         {0, 0, 0, 0}
    };
    
    int option_index = 0;
    char c = getopt_long(argc, argv, "r:h", long_options, &option_index);
    if (c == -1)
    {
        // display help...
        return EXIT_SUCCESS;
    }
    
    do
    {
        switch(c)
        {
            case 'r':
                break;
    
            case 'h':
            {
                // display help...
                return EXIT_SUCCESS;
            }
        }
    
        c = getopt_long(argc, argv, "r:h", long_options, &option_index);
    }
    while (c != -1);
    

    Or this:

    static struct option long_options[] =
    {
         {"r",    required_argument,  0, 'r'},
         {"help", no_argument,        0, 'h'},
         {0, 0, 0, 0}
    };
    
    int option_index = 0;
    char c = getopt_long(argc, argv, "r:h", long_options, &option_index);
    if (c == -1)
        c = 'h';
    
    do
    {
        switch(c)
        {
            case 'r':
                break;
    
            case 'h':
            {
                // display help...
                return EXIT_SUCCESS;
            }
        }
    
        c = getopt_long(argc, argv, "r:h", long_options, &option_index);
    }
    while (c != -1);