为什么这不匹配?
...
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;
}