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.
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;
}
}
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.
eg I get:
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.
'\r'
and'\n'
in many (most) codesets. It's curious you have oneprintf()
printing all that data, but no\n
in the format string. You're relying on the newlines in the data, which seems a little suspect. (Write a function to print the bytes in a string in hex; call it on each string; spot the difference.) – Bellis\n
, you may be off by one if\r\n
is used – Collationr:
line. – ArrowwormreadValue[strcspn(readValue, "\r\n")] = 0;
right after usingfgets(readValue,50,fp)
to eliminate line ending characters. – Kinematographstatic void dump_string(const char *tag, const char *string) { size_t len = strlen(string); printf("%s (%zu):", tag, len); size_t i; for (i = 0; i < len; i++) { printf(" %.2X", (unsigned char)string[i]); if (i % 16 == 15) putchar('\n'); } if (i % 16 != 0) putchar('\n'); }
and call it:dump_string("r", readValue); dump_string("w", longWord);
or similar. – Bellisprintf("'%s'\n", bad_string);
to help identify leading and trailing white-space, new-lines, etc. 2) Rather than thinkingstrcmp()
is wrong, ask why the strings are not equal. – Kinematographfclose()
in your check for the length of the word for cleanup. – Lemgoto
is useful and good practice, e.g.if (some error cond) { ret = -1; goto cleanup; }
– Lem