2010-07-29 25 views
7

我想比較命令的參數與argv [],但它不工作。這是我的代碼。比較命令參數與argv []不起作用

./a.out -d 1 

在主要功能

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

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

    // call some function here 

} 

但是,這是不工作...我不知道爲什麼這種比較是不工作。

+0

見我的答案在這裏:HTTP://計算器.com/questions/3303164/why-isnt-if-maya-maya-true-in-c/3303176#3303176 – 2010-07-29 18:03:37

回答

23

使用==不能比較字符串。相反,使用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

你可能想提一下,C字符串不能被比較的原因是它不會比較內容,只是指針。 – 2010-07-29 18:03:51

+0

或者如果你知道你的參數是單個字母(argv [1] [1] =='d') – 2010-07-29 18:03:55

+0

@Cristian:我編輯了,謝謝你指出。 – Adrian 2010-07-29 18:07:53

-4

將不就是:

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

01

+0

不,因爲'argv'的第一個元素是程序名。 – Adrian 2010-07-29 18:02:48

+1

不,C和C++的char []用於這樣的字符串;它變成了一個指針比較 – 2010-07-29 18:03:05

+1

Nop。首先,你在比較地址,而不是內容。其次,argv [0]是命令路徑。 – ninjalj 2010-07-29 18:03:45

2

你可能想在這裏使用strcmp。

9

在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 

}