Student Programmer Student Programmer - 28 days ago 15
C++ Question

Access to command line user arguments using getopt

I am writing a program that processes options from the user and functions as programmed using getopt. My question is, how do I display an error if the user enters an invalid option? Also, I want to access the variable in order to display it in the error message. Here is a snapshot of my code:

#include <unistd.h>
#include <iostream>

int main(int argc, char **argv)
{
enum {
WHOLE, PREFIX, ANYWHERE, SUFFIX, EMBEDDED
} mode;
bool reverse_match = false;
bool ignore_case = false;
bool specify_length = false;

int c;
while ((c = getopt(argc, argv, "wpsavein:")) != -1) {
switch (c) {
case '?':
std::cerr << "Unrecognised option " << std::endl;
std::cerr << "Usage: match [-OPTION]... PATTERN [FILENAME]..." << std::endl;
return 2;
break;
case 'w': // pattern matches whole word
mode = WHOLE;
break;
case 'p': // pattern matches prefix
mode = PREFIX;
//cout << "test: " << optarg << endl;
break;
case 'a': // pattern matches anywhere
mode = ANYWHERE;
break;
case 's': // pattern matches suffix
mode = SUFFIX;
break;
case 'v': // reverse sense of match
reverse_match = true;
break;
case 'e': // pattern matches anywhere
mode = EMBEDDED;
break;
case 'i': // ignore case
ignore_case = true;
break;
case 'n': // specifies length of match
specify_length = true;
}
}
}


I used the
cerr
stream to display the error, but I would like it to also include user input. For instance if the user input
-t
, the error would be:

Unrecognised option -t
Usage: match [-OPTION]... PATTERN [FILENAME]...


What I am getting is:

invalid option -- 't'
Unrecognised option -t
Usage: match [-OPTION]... PATTERN [FILENAME]...


I believe the
invalid option -- 't'
is the default, but is there a way I can modify or not include it? and also get access to user-specified option?

Answer

Fragment of manual from getopt:

If getopt() does not recognize an option character, it prints an error message to stderr, stores the character in optopt, and returns '?'. The calling program may prevent the error message by setting opterr to 0.

What you need to do:

#include <unistd.h>
#include <iostream>

int main(int argc, char **argv) {
  opterr = 0;
  int c;
  while ((c = getopt(argc, argv, "wpsavein:")) != -1) {
    switch (c) {
      case '?':
        std::cerr << "Unrecognised option -" << static_cast<char>(optopt)
                  << std::endl;
        std::cerr << "Usage: match [-OPTION]... PATTERN [FILENAME]..."
                  << std::endl;
        return 2;
        break;
    }
  }
}