我试图将命令参数与argv []进行比较,但它不起作用。这是我的代码。
./a.out -d 1
在主要功能
int main (int argc, char * const argv[]) {
if (argv[1] == "-d")
// call some function here
}
但这不起作用......我不知道为什么这种比较不起作用。
答案 0 :(得分:25)
您无法使用==
比较字符串。相反,请使用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
。
答案 1 :(得分:10)
在C ++中,让std :: string为你工作:
#include <string>
int main (int argc, char * const argv[]) {
if (argv[1] == std::string("-d"))
// call some function here
}
在C中你必须使用strcmp:
if (strcmp(argv[1], "-d") == 0)
// call some function here
}
答案 2 :(得分:2)
你可能想在这里使用strcmp。
答案 3 :(得分:-4)
不会是:
if (argv[0] == "-d")
0
不是1
?