0

I have a program that parses command line arguments using a while loop. Simply, while iterating through the length of argc, if an argument matches a flag than the next argument is taken as a variable. Now in my assignment we are asked to do this in a way that spaces between flags and integer arguments are optional.

For example if i input -k1 it is the same as -k 1 and 1 is the value stored. I can't find anything that allows this. The only thing I can think is that if argc is an even number it means that there are no pals between a set of argument and i could use scanf("-k%d",key).

Any helpful pointers for me?

5
  • Match -. Get the next character. That is the option flag. If there is anything after that character then the rest is the option value. Do not use scanf for command line args. Use the the standard argc and argv passed to main. Commented Mar 16, 2017 at 23:59
  • You could try sscanf(argv[arg], "-%c%d", &flag, &value) (with arg being the argument number you're checking) and if it returns 2, you have the flag in flag and the value in value... if it returns 1, you have just the flag in flag and can read the next argument to get the value. If it returns anything else, you have a non-matching argument or an error. This would treat something like "-kabc" the same as just "-k", though. Commented Mar 17, 2017 at 0:09
  • @kaylum would that work when arguments are entered as -k 1? or just -k1 Commented Mar 17, 2017 at 0:21
  • You need to handle both cases. If the string ends with an option flag character then the option value is in the next argv entry. Commented Mar 17, 2017 at 0:31
  • If you know what to look for (Google search 'getopt public domain at&t source'), you can find a 1985 (pre-standard, non-prototype) version of getopt(3) which handles program -c 1 -d2 etc, where the option string needs to be c:d: to say "this program takes options -c and -d, and both of them expect an argument. The code is pretty short; it isn't all that complex. Current versions of getopt() tend to be longer, but they're not much more powerful (getopt_long() is a different story). Commented Mar 17, 2017 at 7:07

1 Answer 1

1

At a POSIX-compatible OS you can use a standart API for that: man getopt. It will do all the dirty job to parse the parameters and will provide you a convenient interface to deal with.

Here is a good example for it: http://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html#Example-of-Getopt

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

Comments

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.