我想比較命令的參數與argv [],但它不工作。這是我的代碼。比較命令參數與argv []不起作用
./a.out -d 1
在主要功能
int main (int argc, char * const argv[]) {
if (argv[1] == "-d")
// call some function here
}
但是,這是不工作...我不知道爲什麼這種比較是不工作。
我想比較命令的參數與argv [],但它不工作。這是我的代碼。比較命令參數與argv []不起作用
./a.out -d 1
在主要功能
int main (int argc, char * const argv[]) {
if (argv[1] == "-d")
// call some function here
}
但是,這是不工作...我不知道爲什麼這種比較是不工作。
使用==
不能比較字符串。相反,使用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
。
你可能想提一下,C字符串不能被比較的原因是它不會比較內容,只是指針。 – 2010-07-29 18:03:51
或者如果你知道你的參數是單個字母(argv [1] [1] =='d') – 2010-07-29 18:03:55
@Cristian:我編輯了,謝謝你指出。 – Adrian 2010-07-29 18:07:53
你可能想在這裏使用strcmp。
在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
}
見我的答案在這裏:HTTP://計算器.com/questions/3303164/why-isnt-if-maya-maya-true-in-c/3303176#3303176 – 2010-07-29 18:03:37