getopt总是返回1

Abr*_*ile 2 c++ getopt command-line-arguments

我想提起getopt控制台工具的参数列表。当我如下调用我的工具getopt时,总是返回1并且不破坏任何东西switch/case

难道我做错了什么?

  mytool -f farg -d darg

  int 
  main(int argc, char** argv) {
  int c;
  while((c = getopt(argc, argv, "f:d:h") != -1)) {

      switch(c) {
        case'f':
        break;

        default:
        break;
      }
  }
Run Code Online (Sandbox Code Playgroud)

Sak*_*mar 5

while((c = getopt(argc, argv, "f:d:h") != -1))
Run Code Online (Sandbox Code Playgroud)

它像

c = (getopt(argc, argv, "f:d:h") != -1)
Run Code Online (Sandbox Code Playgroud)

好吧,总是1,因为比较的结果存储到c。在您的情况下,getopt不返回-1。如果返回-1,然后c0。解决方法是

while((c = getopt(argc, argv, "f:d:h")) != -1)
Run Code Online (Sandbox Code Playgroud)