为什么这不匹配

Why does this not match?

本文关键字:不匹配 为什么      更新时间:2023-10-16

为什么这不匹配?

...
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"); 
}

虽然请考虑使用字符串,因为这会给你所需的语义

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

我们需要知道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;
}