2012-04-18 52 views
-1

这为什么不符合?这为什么不符合?

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

输出:

testme 
no 
+4

什么是d_name的类型? – 2012-04-18 13:21:29

+5

考虑到他可以直接将它传递给'puts',我猜它不是'string'。 – 2012-04-18 13:21:51

+0

@JamesMcLaughlin:Touche,但可能会超载。 (不太可能,我知道) – 2012-04-18 13:22:27

回答

6

尝试:

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

或使d_name一个string代替。

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

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; 
} 
+0

海报代码显示由于'puts'输出,'d_name'是'testme''。唯一的错误是他没有使用'strcmp'。 – Pubby 2012-04-18 13:29:10

+0

哦,我现在明白了。谢谢Pubby。 – Chad 2012-04-18 13:36:40