c - strcmp 不为相等的字符串返回 0

c - strcmp not returning 0 for equal strings

所以我尝试广泛地寻找解决方案,但只能真正找到其中一个字符串中缺少新行或空字节的帖子。我很确定这里不是这种情况。

我正在使用以下函数将单词与包含单词列表的文件进行比较,每行一个单词(函数中的字典)。这是代码:

int isWord(char * word,char * dictionary){
  FILE *fp;
  fp = fopen(dictionary,"r");
  if(fp == NULL){
    printf("error: dictionary cannot be opened\n");
    return 0;
  }
  if(strlen(word)>17){
    printf("error: word cannot be >16 characters\n");
    return 0;
  }
  char longWord[18];
  strcpy(longWord,word);
  strcat(longWord,"\n");
  char readValue[50] = "a\n";
  while (fgets(readValue,50,fp) != NULL && strcmp(readValue,longWord) != 0){
    printf("r:%sw:%s%d\n",readValue,longWord,strcmp(longWord,readValue));//this line is in for debugging
  }
  if(strcmp(readValue,longWord) == 0){
    return 1;
  }
  else{
    return 0;
  }
}

代码编译没有错误,函数可以很好地读取字典文件,并打印其中出现的单词列表。我遇到的问题是,即使两个字符串相同,strcmp 也不会 returning 0,因此对于任何输入,该函数都会 return false。

例如我得到:

r:zymoscope
w:zymoscope
-3

有什么想法吗?我觉得我一定遗漏了一些明显的东西,但在我的搜索中找不到任何东西。

我看到您在测试字符串中附加了 newline 以尝试处理 fgets() 保留行尾的问题。从源头上解决这个问题要好得多。您可以像这样在读取文件后立即删除所有尾随内容。

readValue [ strcspn(readValue, "\r\n") ] = '[=10=]';   // remove trailing newline etc

您正在读取的字符串包含尾随字符,因此与您正在比较的字符串不同。

删除结尾的换行符(如果有,则删除 CR);那么你不需要在被比较的字符串中添加任何换行符或回车符 return:

int isWord(char *word, char *dictionary){
  FILE *fp;
  fp = fopen(dictionary, "r");
  if (fp == NULL){
    fprintf(stderr, "error: dictionary cannot be opened\n");
    return 0;
  }
  if (strlen(word) > 16){
    fprintf(stderr, "error: word cannot be >16 characters\n");
    return 0;
  }
  char readValue[50];
  while (fgets(readValue, 50, fp) != NULL){
    char *ep = &readValue[strlen(readValue)-1];

    while (*ep == '\n' || *ep == '\r'){
      *ep-- = '[=10=]';
    }
    if (strcmp(readValue, word) == 0){
      return 1;
    }
  }
  return 0;
}