米哈游 2022-04-12 13:46 采纳率: 100%
浏览 66
已结题

在TXT文本中查找特定汉字,总是输出0不知道哪里错了


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 40
int main()
{
int i,count = 0;
char *cSource,*cSearch;
FILE *fp;
cSource = (char *)malloc(N * sizeof(char));
cSearch = (char *)malloc(3 * sizeof(char));
if((fp = fopen("word.txt", "r")) == NULL)
{
printf("文件打开失败!\n");
exit(0);
}
printf("输入统计的汉字:");
scanf("%s", cSearch);
fgets(cSource, N, fp);
for(i = 0; i < (int)strlen(cSource); i++)
{
if(cSource[i] == cSearch[0] && cSource[i+1] == cSearch[1])
//一个汉字占两个字节 所以需要判断两个字节的内容
count++;
}
printf("%d\n", count);
return 0;
}
  • 写回答

3条回答 默认 最新

  • 关注

    fgets读取一行,你的文件中只有1行吗?另外,这一行中只有汉字,没有别的字符吗,这么比较是不对的

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 4月20日
  • 已采纳回答 4月12日
  • 创建了问题 4月12日