0

I have written the code below however the strcmp function is not working properly. It is not picking up known text from a text file and returns 0 for the word count.

int count = 0;
char line[400];
char word[20];

printf("Search for? \n");
scanf_s("%s", word, 19);

if (Fp == NULL)
{
    printf("File not found");
}
while (!feof(Fp))
{
    fgets(line, 150, Fp);

    if (strcmp(line, word) == 0) //searches the line to find word
    {
        count++;//increment
    }
}

printf("Search returned %s was found %d number of times", word, count);
Zimmer
  • 1
  • 1
  • 4
    Note that `line` contains a newline. and Read [Why is “while ( !feof (file) )” always wrong?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – BLUEPIXY Dec 01 '16 at 19:27

2 Answers2

3

Do not use the strcmp(), try this instead:

if (strstr(line, word)) { ... } 
S.Pot
  • 31
  • 3
1

Well, strcmp() doesn't do what you may think it does. Your code comments say it searches for the word in the line; that's incorrect. strcmp just gives an indication if the two strings you pass it are identical (or, if not, which would come first in a sort).

Mark Adelsberger
  • 42,148
  • 4
  • 35
  • 52