Ç - STRCMP不是等于字符串返回0 [英] c - strcmp not returning 0 for equal strings

查看:270
本文介绍了Ç - STRCMP不是等于字符串返回0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我已经试过了广泛寻找一个解决这个,但真的只能找到岗位,其中新行或空字节从琴弦一人失踪。我相当肯定这里并非如此。

So I've tried searching for a solution to this extensively but can only really find posts where the new line or null byte is missing from one of the strings. I'm fairly sure that's not the case here.

我使用下面的函数到字比较含有单词列表,每行(在功能字典)一个字的文件。这里是code:

I am using the following function to compare a word to a file containing a list of words with one word on each line (dictionary in the function). Here is the code:

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;
  }
}

在code没有错误编译和函数读取字典文件罚款,因为他们出现在那里将打印单词列表。我遇到的问题是,即使在两个字符串相同,STRCMP没有返回0,因此该函数将返回false任何输入。

The code compiles with no errors and the function reads the dictionary file fine and will print the list of words as they appear in there. The issue I am having is that even when the two strings are identical, strcmp is not returning 0 and so the function will return false for any input.

比如我得到:

r:zymoscope
w:zymoscope
-3

任何想法?我觉得我必须失去了一些东西明显,但一直无法在我的搜索,以发现任何东西。

Any ideas? I feel like I must be missing something obvious but have been unable to find anything in my searches.

推荐答案

我看你追加换行来测试字符串来试图解决的问题与fgets()保留行尾。要好得多,从源头解决这个问题。您可以去除所有尾随这样的东西,从文件中读取后立即

I see you are appending a newline to your test strings to try to deal with the problem of fgets() retaining the line endings. Much better to fix this at source. You can strip all trailing stuff like this, immediately after reading from file.

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

这篇关于Ç - STRCMP不是等于字符串返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆