0

I'm trying to use getopt to parse my command line arguments but i'm having an issue where it is setting the wrong values its skipping case 1 and setting case 2 as case 1.Here is the while loop of just the cases. The flags work fine its just reading in by position that is the problem.

while ((c = getopt (argc, argv, "-l:u:eo")) != -1)
         switch (c)
           {
           case 1:
            printf("here\n");
             lower = atoi(optarg);
             break;
           case 2:
             upper = atoi(optarg);
             break;
    }

here is the output from the terminal after running the program.

(%) fibon 12 22
here
here
lower = 22, upper = 0, even = 0, odd = 0
Usage: fibon[[lower upper] | [-l lower -u upper]] [-e|-o]

1 Answer 1

1

From the getopt(3) manual page:

If the first character of optstring is '-', then each nonoption argv-element is handled as if it were the argument of an option with character code 1.

That means that both numbers will be returned from getopt as 1. You need to keep track of which option you have yourself.

Sign up to request clarification or add additional context in comments.

3 Comments

can you clarify more i don't understand how to keep track of the options
@user3400512 Keep a counter, initialized to 1. If it's 1 its the first value and you increase the counter. If it's 2 it's the second value. Etc.
i tried doing the counter and when counter is 1 lower = atoi(argv[1]) and increment the counter and do the same for when counter is 2 but it still isn't working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.