简体   繁体   中英

Reading words of a .txt file not working C

I wanted to search for specific words in a .txt file.

For example the file includes "Jon Miller, Andy Miller, Apu McDawn" And I want to search for "Miller" in this file how often it occures. then it should show me the number (num) "2"

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

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

    FILE *in_file = fopen("test.txt", "r"); //reading the words

    if (in_file == NULL)
    {
        printf("Dataerror\n"); //if word not found
        exit(-1);
    }

    else {
        scanf("%s", word);
        printf("%s\n", word);

        while(!feof(in_file))//search for the word

        {
            fscanf(in_file,"%s", string);
            if(!strcmp(string , word))//if hit a word
            num++;
        }

        printf( "%d Hit \n" ,num );
    }
    return 0;
}

You haven't allocated any memory for string . Change

char *string;

To

char string[100];

Or allocate memory dynamically

string=malloc(100);

And free it after its use using

free(string);

Also change

while(!feof(in_file))

To

while(fscanf(in_file,"%s", string))

And remove the fscanf inside the body of this loop. Read this to know why I've made that change. And include string.h in your program.

My friend i have just changed the function strcmp to strncmp. & it works. Both these functions compare two strings. strcmp() compares the entire string down to the end, while strncmp() only compares the first n characters of the strings.nction strcmp to strncmp.

It's a little funky what they return. Basically it's a difference of the strings, so if the strings are the same, it'll return zero (since the difference is zero). It'll return non-zero if the strings differ; basically it will find the first mismatched character and return less-than zero if that character in string is less than the corresponding character in word. It'll return greater-than zero if that character in string is greater than that in word.

 #include <stdio.h>
 #include <stdlib.h>
 int main(int argc, char const *argv[])
 {   
int num =0;

char word[100];

char *string;

FILE *in_file = fopen("ser.txt", "r"); //reading the words

if (in_file == NULL)
{
    printf("Dataerror\n"); //if word not found
    exit(-1);
}

else {
    scanf("%s", word);
    printf("%s\n", word);

    while(!feof(in_file))//search for the word

    {
        fscanf(in_file,"%s", string);
        if(!strncmp(string , word))//if hit a word
        num++;
    }

    printf( "%d Hit \n" ,num );
}
return 0;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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