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!
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.