0

is there a builtin way to make an argument depend on another when using getopt? For example, I have my switch case setup and everything works fine, but I need my -m argument (the length of the markov chain) before I read a text file (-i).

In other words, I would like to make sure that other arguments aren't set when processing my input arg.

Small excerpt:

    while ((opt = getopt_long(argc, argv, "i:shm:", long_options, &option_index))
       != -1)
{
    switch (opt) {
        case 'i':
            inputEnglish.ReadFile((string)optarg);
            break;

        case 'm':
            inputEnglish.setMarkovLength(atoi(optarg));
            break;

        case 's':
            break;

        case 'h':
            printHelp();
            break;

        case '?':
            cout << "dfgdfgdf" << endl;
            return 0;
            break;

        default:
            printHelp();
            return 0;
            break;
    }
}

If there aren't any built-in ways, do you have a clean way of doing this? Clean code being more important than efficiency here. Thank you for any help!

scx
  • 3,221
  • 1
  • 19
  • 37

1 Answers1

1

Save the file name and only process it after you have processed all the command line arguments. This is generally the best approach -- the getopt code should only parse, not process.

Alternatively, and this is the way most commands work, don't use a flag for the filename ... so the usage is pgm -m foo filename. Then you just process the remaining arguments (argv[optind] through argv[argc-1]) as filenames after you've processed all the flags. This is conducive to the common situation -- like yours -- of the processing of a file depending on the flag values.

Jim Balter
  • 16,163
  • 3
  • 43
  • 66
  • Two more possibilities are: (1) check whether the `-m` option has been set before running the action in the `-i` option handling code, and (2) define a suitable default Markov length that is used if you don't define one with `-m` before specifying the file with `-i`. On the whole, though, it is best to handle options (and defaults) and then process files. GNU [`getopt()`](http://www.gnu.org/software/libc/manual/html_node/Getopt.html#Getopt) has a mode that returns file names as if they were option arguments; I've not tested whether `getopt_long()` behaves similarly. – Jonathan Leffler Mar 04 '14 at 06:10
  • Thank you very much! I had the feeling that was the right thing to do, but wasn't quite sure how to go about it. Great answer and comment. – scx Mar 04 '14 at 06:17