Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么这不匹配?_C++ - Fatal编程技术网

C++ 为什么这不匹配?

C++ 为什么这不匹配?,c++,C++,为什么这不匹配 ... puts (ep->d_name); if(ep->d_name=="testme"){ printf("ok"); } else { printf("no"); } ... 输出: testme no 尝试: 或者将d_name改为string。发生这种情况是因为您正在比较两个指针,它们指向具有相同值的字符* 你真的应该这么做 puts (ep->d_name); if(strcmp(ep->d_name, "testme")==0){

为什么这不匹配

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

testme
no
尝试:


或者将
d_name
改为
string

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

你真的应该这么做

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;
}
/*strcmp示例*/
#包括
#包括
int main()
{
char szKey[]=“苹果”;
字符输入[80];
做{
猜一猜我最喜欢的水果;
获取(szInput);
}而(strcmp(szKey,szInput)!=0);
放置(“正确答案!”);
返回0;
}

考虑到他可以直接将它传递给
puts
,我猜它不是
字符串
@JamesMcLaughlin:Touche,但可能会过载。(不太可能,我知道)dyNeX是一个256字符数组()@ Paulr:坏C++,但仍然是C++。为什么问题的投票率下降?看起来对我有效。可能遗漏了变量类型,但仍然存在。由于
puts
输出,海报代码显示
d_name
“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;
}