这为什么不符合?这为什么不符合?
...
puts (ep->d_name);
if(ep->d_name=="testme"){ printf("ok"); } else { printf("no"); }
...
输出:
testme
no
这为什么不符合?这为什么不符合?
...
puts (ep->d_name);
if(ep->d_name=="testme"){ printf("ok"); } else { printf("no"); }
...
输出:
testme
no
尝试:
if(!strcmp(ep->d_name, "testme"))
或使d_name
一个string
代替。
发生这种情况是因为你比较两个指针,其指向的char *具有相同值
你应该做的
puts (ep->d_name);
if(strcmp(ep->d_name, "testme")==0){
printf("ok");
}
else {
printf("no");
}
虽然请考虑使用字符串,这将使你语义你需要
我们需要知道正在与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;
}
什么是d_name的类型? – 2012-04-18 13:21:29
考虑到他可以直接将它传递给'puts',我猜它不是'string'。 – 2012-04-18 13:21:51
@JamesMcLaughlin:Touche,但可能会超载。 (不太可能,我知道) – 2012-04-18 13:22:27