在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;
}

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

//一个汉字占两个字节 所以需要判断两个字节的内容----------先确定一个汉字占几个字节
char ch[] = "中";
int len = strlen(ch);
你测试一下,len等于几

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632