Getopt总是返回1

getopt always returns 1

本文关键字:返回 Getopt      更新时间:2023-10-16

我想使用getopt获取我的控制台工具的参数列表。当我像下面的getopt一样调用工具时,请始终返回1,并且不会mactch任何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;
      }
  }
while((c = getopt(argc, argv, "f:d:h") != -1))

它像

一样工作
c = (getopt(argc, argv, "f:d:h") != -1)

好吧,这总是1,因为比较的结果存储到c。在您的情况下,getopt不返回-1。如果返回-1,则c将为0。修复是

while((c = getopt(argc, argv, "f:d:h")) != -1)