gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:20:31 25 4
gpt4 key购买 nike

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

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

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 也不会返回 0,因此该函数对于任何输入都将返回 false。

例如我得到:

r:zymoscope
w:zymoscope
-3

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

最佳答案

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

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

关于c - strcmp 不为相等的字符串返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31660585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com