#parsing options from stdin

19 messages · Page 1 of 1 (latest)

magic vine
#

Im creating a program that shows a prompt and then based on the input does something
the input is something like (option) Ni [Nj Nk ...] eg insert Ni Nj each option can be an entire string, eg insert,find,modify or can have a shorthand i,f,m (the previous example is equivelant to i Ni Nj) (shorthands are 1-2 charachters long)

Is there any smart way to parse this input? I feel like a bunch of else ifs with strcmp isnt the answer...

winter iglooBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

frigid lantern
#

I wouldn't say it is super bad, bunch of strcmp, another possibility is to make a struct and build a table to scan with elements like {"insert", 'i', function_handling_insert}

#

then there's a question if you feel a need to do faster string search, then you may e.g. consider using glib as it has hash tables, so no need to reinvent the wheel

#

well, I mean if all would be unique on first character then it is not much of a job for searching

magic vine
magic vine
magic vine
frigid lantern
#
[
  {"insert", 'i', function_handling_insert},
  {"remove", 'r', function_handling_remove}
]
#

you can just iterate over it

magic vine
#

yeah I get it, this should make the code more readable, but still seems off

#

I feel like there should be something better, maybe im wrong

frigid lantern
#

I mean besides going into more elaborate data structures to find elements faster I don't think there is

magic vine
#

what about parsing command line arguments? eg -i inputfile and -o outfile and more options which could be in random order when executing the program? eg $ ./foo -i bar -o baz

winter iglooBOT
#

getopt, getopt_long, getopt_long_only, optarg, optind, opterr, optopt - Parse command-line options

Synopsis
#include <unistd.h>

int getopt(int argc, char *const argv[],
           const char *optstring);

extern char *optarg;
extern int optind, opterr, optopt;

#include <getopt.h>

int getopt_long(int argc, char *const argv[],
           const char *optstring,
           const struct option *longopts, int *longindex);
int getopt_long_only(int argc, char *const argv[],

... (truncated)

frigid lantern
#

that's my go to

#

both because I like the convention used and to not reinvent the wheel

marble grail