Jakkie Chan
Jakkie Chan

Reputation: 317

how to make a C program accept an option once

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

int main(int argc, char *argv[])
{
if (argc == 1)
{
    printf("You must supply -m, -f, or -l\n");
    return 1;
}

for (int i = 1; i < argc; i++)
{
    if (strcmp(argv[i], "-l") == 0)
    {
        printf("Salve\n");
    }
    else if (strcmp(argv[i], "-f") == 0)
    {
        printf("Bonjour\n");
    }
    else if (strcmp(argv[i], "-m") == 0)
    {
        printf("Howdy\n");
    }
    else if (strcmp(argv[i], "-d") == 0)
    {
        printf("Derp\n");
    }
    else
    {
        printf("Use -m, -f, or -l\n");
        return 1;
    }
}

return 0;

}

So I want to make it so when you do ./greet -m -m -d, it well print howdy once and derp once, ignoring the second -m option. How am i able to do something like that?

Upvotes: 0

Views: 98

Answers (2)

kave
kave

Reputation: 471

The simplest way that comes to my mind would be to set int m_set = 0 somewhere at the beginning and do

....
else if (strcmp(argv[i], "-m") == 0 && m_set == 0)
{
    printf("Howdy\n");
    m_set = 1
}
...

In that case the else statement at the end will be executed. To prevent that, you could make it an else if(m_set == 0)

Another approach that does what you need uses continue

int m_set = 0
....
else if (strcmp(argv[i], "-m") == 0)
{
    if(m_set == 1)
        continue;
    printf("Howdy\n");
    m_set = 1;
}
...

Upvotes: 3

Phil Perry
Phil Perry

Reputation: 2130

Instead of immediately taking action when processing a flag in the command line, just set a code flag that it was seen (initialize to FALSE). Or increment a counter, if you want to flag excess uses of the flag. You can handle conflicting flags on the fly (-a and -b are mutually exclusive, and while processing -b, your a-flag says you've already given -a). After you have processed the command line, you can loop through the flags and perform the actions. Does the order of the flag matter?

Upvotes: 3

Related Questions