代码之家  ›  专栏  ›  技术社区  ›  itsaboutcode

将命令参数与argv[]进行比较不起作用

c c++
  •  9
  • itsaboutcode  · 技术社区  · 14 年前

    我试图将command的参数与argv[]进行比较,但它不起作用。这是我的密码。

    ./a.out -d 1
    

    在主功能中

    int main (int argc, char * const argv[]) {
    
    if (argv[1] == "-d")
    
        // call some function here
    
    }
    

    但这不管用。。。我不知道为什么这个比较不起作用。

    4 回复  |  直到 14 年前
        1
  •  28
  •   Adrian    14 年前

    == . 相反,使用 strcmp .

    #include <string.h>
    
    int main (int argc, char * const argv[]) {
    
    if (strcmp(argv[1], "-d") == 0)
    
    // call some function here
    
    }
    

    原因是 "..." "-d" argv[1] 不一样, 会回来的 0

        2
  •  13
  •   Mark B    14 年前

    在C++中,让STD::String为您做工作:

    #include <string>
    int main (int argc, char * const argv[]) {
    
    if (argv[1] == std::string("-d"))
    
    // call some function here
    
    }
    

    if (strcmp(argv[1], "-d") == 0)
    
    // call some function here
    
    }
    
        3
  •  2
  •   Brandon Horsley    14 年前

    你可以在这里用strcmp。

        4
  •  -4
  •   chown    13 年前

    那不是:

    if (argv[0] == "-d")
    

    0 1