[英]Counting the occurrences of a word from a text file in C
The following code is intended to find the occurrences of the word 'if' from a text file chosen by the user, however the result after exiting the loop is always 0. Question is how it could be possibly fixed. 以下代码旨在从用户选择的文本文件中查找单词“ 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");
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;
}
'if'
isn't what you think it is; 'if'
不是您认为的那样; it's a multicharacter literal, not a string. 这是一个多字符文字,而不是字符串。
You can't compare strings with ==
in C. Use strcmp(3)
. 您无法在C中将字符串与==
进行比较。请使用strcmp(3)
。
Your loop doesn't look like it does what you want either; 您的循环看起来也不像您想要的那样。 time to break out a debugger (and probably strtok(3)
). 是时候启动调试器了(可能还有strtok(3)
)。
For one thing, read[i]
only contains a single character and will never be equal to any multi-character word. 一方面, read[i]
仅包含一个字符,并且永远不会等于任何多字符单词。
For another, single apostrophe's are used to define single characters. 另外,单个撇号用于定义单个字符。 'if'
is not a string of characters. 'if'
不是字符串。
You will need to parse each line to find each individual word, and then compare each word to the target word using something like stricmp()
. 您将需要解析每一行以找到每个单词,然后使用诸如stricmp()
类的单词将每个单词与目标单词进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.