Reputation: 175
For part of a program that I am writing, I need to search a text file to see if a certain word exists in the file, and if it does, I want to print it to the screen. Why is using a for loop to string compare such as this:
int in_dictionary(char dict[][8], char word[], int size) {
int i;
for (i = 0; i<size; i++)
if (strcmp(word, dict[i]) == 0){
return 0;
}
else{
return 1;
}
}
Not working for me?
Upvotes: 1
Views: 994
Reputation: 454990
When strcmp()
returns a 0
then it means a match was found. At that time you need to return a 1
and not 0
. Also if strcmp()
returns 1
it means that the current element in the dictionary did not match the search string, at which point you cannot conclude that a match does not exist in the dictionary, it may come later. So only when you've compared the search string with all the elements in the dictionary and not found any match can you conclude that the search string is not in the dictionary.
You need:
for (i = 0; i<size; i++)
if (strcmp(word, dict[i]) == 0){
return 1;
}
return 0;
Upvotes: 2
Reputation: 400224
You're only comparing the first word in the dictionary to the word you're searching for. You should only return failure after comparing all of the words:
for(...) {
if(dict[i] matches)
return MATCH;
}
return NO_MATCH;
Also, your return values are backwards -- typically, you'd return 0 to indicate failure (no match) and return 1 to indicate success (match). The exceptions to that are the main()
function, by convention, and many POSIX system calls (which return 0 for success and -1 for failure).
Upvotes: 6