在c中的文件中搜索字符串

jim*_*imo 4 c string search string-search data-structures

我正在尝试编写一个可以搜索文件(称为student.txt)中的字符串的程序。我希望我的程序在文件中找到相同的单词时打印该单词,但它显示错误。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
int num =0;
char word[2000];
char *string[50];

FILE *in_file = fopen("student.txt", "r");
//FILE *out_file = fopen("output.txt", "w");

if (in_file == NULL)
{
    printf("Error file missing\n");
    exit(-1);
}

while(student[0]!= '0')
{
    printf("please enter a word(enter 0 to end)\n");
    scanf("%s", student);


    while(!feof(in_file))
    {
        fscanf(in_file,"%s", string);
        if(!strcmp(string, student))==0//if match found
        num++;
    }
    printf("we found the word %s in the file %d times\n",word,num );
    num = 0;
}

return 0;
 } 
Run Code Online (Sandbox Code Playgroud)

Ans*_*hul 5

添加了最简单形式的示例代码。处理任何极端情况。如果您正在搜索字符串“to”。文件内容是:

<tom took two tomatoes to make a curry> . 
Run Code Online (Sandbox Code Playgroud)

输出结果为 5。但实际上只有一个单词“to”。

代码:

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char const *argv[])
{
        int num =0;
        char word[2000];
        char string[50];
        char student[100] = {0};

        while(student[0]!= '0')
        {
                FILE *in_file = fopen("student.txt", "r");
                if (in_file == NULL)
                {
                        printf("Error file missing\n");
                        exit(-1);
                }

                printf("please enter a word(enter 0 to end)\n");
                scanf("%s", student);
                while ( fscanf(in_file,"%s", string) == 1)
                {
                        //Add a for loop till strstr(string, student) does-not returns null. 
                        if(strstr(string, student)!=0) {//if match found
                                num++;
                        }
                }
                printf("we found the word %s in the file %d times\n",student,num );
                num = 0;
                fclose(in_file);
        }
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

正如我的同事所说,我们需要再有一个循环来遍历同一行中同一单词的任何进一步实例。

注意:如果您只想计算单词“to”,请确保检查“string - 1”和“string + 1”字符以查找所有可能的单词分隔符,例如空格、逗号、句号、换行符、感叹号、与号、等于号和任何其他可能性。一种简单的方法是使用 strtok,它会根据参数中指定的分隔符将缓冲区标记为单词。查看如何使用 strtok。

http://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm