简体   繁体   English

在文本文件中搜索C中的字符串

[英]Searching a text file for a string in C

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: 为什么使用for循环来进行字符串比较,例如:

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? 不为我工作?

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). 同样,您的返回值是后退的-通常,您将返回0表示失败(不匹配),而返回1表示成功(匹配)。 The exceptions to that are the main() function, by convention, and many POSIX system calls (which return 0 for success and -1 for failure). 根据惯例, main()函数和许多POSIX系统调用是例外(它们返回0表示成功,-1表示失败)。

When strcmp() returns a 0 then it means a match was found. strcmp()返回0 ,表示已找到匹配项。 At that time you need to return a 1 and not 0 . 那时您需要返回1而不是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. 同样,如果strcmp()返回1则表示字典中的当前元素与搜索字符串不匹配,这时您不能得出字典中不存在匹配项的结论,它可能稍后出现。 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM