2014-03-04 25 views
1

在以下工作代码中;而是采用*tofind,如果我直接使用比较为什么直接比较字符串失败,但成功使用char *

if(*argv[i] == "and")

失败。

为什么会这样?

/** 
* Find index of the word "and" 
* ./a.out alice and bob 
*/ 
int main(int argc, char **argv) { 
    int i = 0; 
    char *tofind = "and"; 
    while (argv[i] != NULL) { 
     if(*argv[i] == *tofind) { 
      printf("%d\n", i + 1); 
      break; 
     } 
     ++i; 
    } 
    return 0; 
} 
+0

您可以直接比较'char'不串字符串比较使用'strcmp'看更多http://www.cplusplus.com/reference/cstring/strcmp/ –

回答

2

if(*argv[i] == "and")不应编译,我想你的意思if (argv[i] == "and"),将两者进行比较,而不是字符串内容的指针。

if (*argv[i] == *tofind)无法按预期方式工作,它只比较第一个字符。

比较字符串,使用strcmp()

if (strcmp(argv[i], tofind) == 0) 
0

A “字符*” 正式指向一个单个字符,例如找到指向一个字母 'A'。你知道还有两个字符和一个字符,但是它正式指向了一个字符。

因此,* argv [i]是参数的第一个字符,* tofind总是字母'a',所以您的代码会检查参数的第一个字符是否为'a'。看看strcmp函数,它比较整个字符串。

0

看的

*argv[i] //its type is char 

的类型和 “和”

"and" //its type is const char * as it is decayed into pointer 

所以这就是为什么你不能对它们进行比较。 而

*tofind 

类型为char,现在您可以比较two.for更多详情,请参见常见问题解答第6节