所以我试图广泛地搜索这个解决方案,但只能找到其中一个字符串中缺少新行或空字节的帖子.我很确定这不是这种情况.
我使用以下函数将一个单词与一个文件进行比较,该文件包含每行一个单词的单词列表(函数中的字典).这是代码:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
代码编译时没有错误,函数会很好地读取字典文件,并打印出现在那里的单词列表.我遇到的问题是,即使两个字符串相同,strcmp也不会返回0,因此函数将为任何输入返回false.
我得到:
r:zymoscope
w:zymoscope
-3
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?我觉得我必须遗漏一些显而易见但却无法在搜索中找到任何内容的东西.
我看到你正在附加一个newline测试字符串来试图解决fgets()保留行结尾的问题.从源头上解决这个问题要好得多.您可以在从文件中读取后立即删除所有这样的尾随内容.
readValue [ strcspn(readValue, "\r\n") ] = '\0'; // remove trailing newline etc
Run Code Online (Sandbox Code Playgroud)