-1

为什么这不匹配?

...
puts (ep->d_name);
if(ep->d_name=="testme"){ printf("ok"); } else { printf("no"); }
...

输出:

testme
no
4

3 回答 3

6

尝试:

if(!strcmp(ep->d_name, "testme"))

d_name改为string

于 2012-04-18T13:22:47.097 回答
6

发生这种情况是因为您正在比较两个指针,它们指向具有相同值的 char*

你真的应该做

puts (ep->d_name);
if(strcmp(ep->d_name, "testme")==0){ 
    printf("ok"); 
}
else { 
    printf("no"); 
}

尽管请考虑使用字符串,因为这将为您提供所需的语义

http://en.cppreference.com/w/cpp/string/basic_string

于 2012-04-18T13:23:18.657 回答
1

我们需要知道 d_name 传递了什么值。

对于打印“ok”的程序,该值也需要是“testme”。

另外,查看这个函数:strcmp。它比较两个字符串,这基本上就是您在这里所做的。

例子:

    /* strcmp example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char szKey[] = "apple";
  char szInput[80];
  do {
     printf ("Guess my favourite fruit? ");
     gets (szInput);
  } while (strcmp (szKey,szInput) != 0);
  puts ("Correct answer!");
  return 0;
}
于 2012-04-18T13:26:26.287 回答