计算C中文本文件中某个单词的出现次数
以下代码旨在从用户选择的文本文件中查找单词“if”的出现情况,但是退出循环后的结果始终为0。问题是它怎么可能被修复计算C中文本文件中某个单词的出现次数,c,C,以下代码旨在从用户选择的文本文件中查找单词“if”的出现情况,但是退出循环后的结果始终为0。问题是它怎么可能被修复 #include<stdio.h> #include<conio.h> #include<string.h> int main() { FILE * f; int count = 0, i; char buf[50], read[100]; printf("Which file to open\n"); f
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main() {
FILE * f;
int count = 0, i;
char buf[50], read[100];
printf("Which file to open\n");
fgets(buf, 50, stdin);
buf[strlen(buf) - 1] = '\0';
if (!(f = fopen(buf, "rt"))) {
printf("Wrong file name");
} else printf("File opened successfully\n");
for (i = 0; fgets(read, 100, f) != NULL; i++) {
if (read[i] == 'if') count++;
}
printf("Result is %d", count);
getch();
return 0;
}
#包括
#包括
#包括
int main(){
文件*f;
int计数=0,i;
char buf[50],读取[100];
printf(“要打开的文件\n”);
fgets(buf,50,标准偏差);
buf[strlen(buf)-1]='\0';
如果(!(f=fopen(buf,“rt”)){
printf(“错误的文件名”);
}else printf(“文件已成功打开\n”);
对于(i=0;fgets(read,100,f)!=NULL;i++){
如果(读[i]=“如果”)计数++;
}
printf(“结果为%d”,计数);
getch();
返回0;
}
“如果”
不是你想象的那样;它是多字符文字,而不是字符串==
进行比较。请使用strcmp(3)
strtok(3)
)if (read[i]=='if') /* no */
使用
首先,
read[i]
只包含一个字符,永远不会等于任何多字符单词
另一方面,单撇号用于定义单个字符<代码>“如果”不是字符串
您需要解析每一行以找到每个单词,然后使用类似于
stricmp()
的方法将每个单词与目标单词进行比较,也无需编写buf[strlen(buf)-1]='\0'代码>。为什么?我不这么认为。它根本无法成功打开文件。返回if语句-“错误的文件名”。如果一个句子包含单词“cliff”,该怎么办?因为“cliff”包含“if”,所以这算是一次成功吗?好吧,这很有效。谢谢你的回答!事实上,这就是我在(fscanf(f,,%s,&next)!=EOF){if(strcmp(read,“if”)==0)count++时所做的更改;也许我也没有正确地使用for循环。
if (strcmp(read[i], "if") == 0) /* check if the strings are equal */