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

its*_*ode 10 c c++

我试图将命令的参数与argv []进行比较,但它不起作用.这是我的代码.

./a.out -d 1
Run Code Online (Sandbox Code Playgroud)

在主要功能

int main (int argc, char * const argv[]) {

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

    // call some function here

}
Run Code Online (Sandbox Code Playgroud)

但这不起作用......我不知道为什么这种比较不起作用.

Adr*_*ian 26

您无法使用比较字符串==.相反,使用strcmp.

#include <string.h>

int main (int argc, char * const argv[]) {

if (strcmp(argv[1], "-d") == 0)

// call some function here

}
Run Code Online (Sandbox Code Playgroud)

原因是值"..."是一个指针,表示字符串中第一个字符的位置,其后的其余字符."-d"在代码中指定时,它会在内存中生成一个全新的字符串.由于新字符串的位置和argv[1]不一样,==将返回0.

  • 您可能想提一下,C 字符串无法比较的原因是因为它不比较内容,只比较指针。 (2认同)

Mar*_*k B 11

在C++中,让std :: string为你工作:

#include <string>
int main (int argc, char * const argv[]) {

if (argv[1] == std::string("-d"))

// call some function here

}
Run Code Online (Sandbox Code Playgroud)

在C中你必须使用strcmp:

if (strcmp(argv[1], "-d") == 0)

// call some function here

}
Run Code Online (Sandbox Code Playgroud)