4
#include <iostream>
#include <getopt.h>

#define no_argument 0
#define required_argument 1 
#define optional_argument 2


int main(int argc, char * argv[])
{
  std::cout << "Hello" << std::endl;

  const struct option longopts[] =
  {
    {"version",   no_argument,        0, 'v'},
    {"help",      no_argument,        0, 'h'},
    {"stuff",     required_argument,  0, 's'},
    {0,0,0,0},
  };

  int index;
  int iarg=0;

  //turn off getopt error message
  opterr=1; 

  while(iarg != -1)
  {
    iarg = getopt_long(argc, argv, "svh", longopts, &index);

    switch (iarg)
    {
      case 'h':
        std::cout << "You hit help" << std::endl;
        break;

      case 'v':
        std::cout << "You hit version" << std::endl;
        break;

      case 's':
        std::cout << "You hit stuff" << std::endl;
        break;
    }
  }

  std::cout << "GoodBye!" << std::endl;

  return 0; 
}

出力:

./a.out -s
Hello
You hit stuff
GoodBye!

出力:

./a.out --stuff
Hello
./a.out: option `--stuff' requires an argument
GoodBye!

競合を解決する必要があります: -s と --s の両方を次のように指定する必要があります: ./a.out: オプション `--stuff' は、コマンドの後に引数を続行せずに使用する場合、引数が必要です。しかし、 --stuff だけですか? ここで何が欠けているか知っている人はいますか?

望ましい結果:

./a.out -s
     Hello
     ./a.out: option `--stuff' requires an argument
      GoodBye!

./a.out --stuff
     Hello
     ./a.out: option `--stuff' requires an argument
     GoodBye!
4

2 に答える 2

8

getopt_long 呼び出しでは、短いオプションとして "s:vh" を指定する必要がありますが、"svh" を指定します。コロンは、"s" の引数が必要であることを getopt に伝えます。

于 2012-01-09T18:12:54.177 に答える
4

「svh」を「s:vh」に置き換える必要があると確信しています。getopt_long の Linux マニュアル ページによると、「optstring は正当なオプション文字を含む文字列です。そのような文字の後にコロンが続く場合、オプションには引数が必要です」。

于 2012-01-09T18:11:38.600 に答える