将 fgets() 与 strcmp() 一起使用 strcmp 不能正确比较 - C 编程

问题描述 投票:0回答:1

我当前的任务是编写一个函数,该函数给定一个 FILE 指针和一个指向字符串的指针。该函数应分析该字符串在给定文件中出现的次数并以整数形式返回该值。它还需要注意区分大小写。在我当前的程序中,我将单词“dog”作为要在文件中找到的字符串。但即使 .txt 文件中出现了 3 次狗这个词,它仍然给我 0。这是我在这里的第一篇文章,我检查了有关此主题的其他帖子,但他们无法修复它,我希望你能帮助我。非常感谢你

这就是我尝试过的:

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

int searchAndCount(FILE *fp, const char *searchWord){
    int count = 0;
    char buffer[4096];
    
    while((fgets(buffer,sizeof(buffer),fp))!=NULL){ 
        buffer[strlen(buffer)-1] = '\0';
        if (strcmp(buffer, searchWord) == 0) {
            count++;
        }
    }
    return count;
}


int main(){

    FILE *fp;
    int searchedWord;
    const char *c = "dog";
    
    fp = fopen("test.txt", "r");
    if (fp == NULL) {
        perror("File couldn't open properly");
        return 1;
    }
    searchedWord = searchAndCount(fp, c);
    printf("The word 'dog' occurs %d-times in the file\n", searchedWord);

    fclose(fp);


    return 0;
}

我的 test.txt 看起来像这样:

dog dog dogoggo dog.

我明白了:

The word 'dog' occurs 0-times in the file
c fgets strcmp
1个回答
0
投票

代替

strcmp()
(如果输入行 则可以匹配),请使用
strstr()
查找多次出现的情况。

当输入行为

s++
并且按键为
"ababa\n"
时,下面的代码使用
"aba"
来计数 2。

while (fgets(buffer, sizeof buffer, fp)) { 
  char *s = buffer;
  while (*s) {
    if (strstr(s, searchWord)) {
      count++;
    }
    s++; 
  }
}
return count;
© www.soinside.com 2019 - 2024. All rights reserved.