以下代碼旨在從用戶選擇的文本文件中查找單詞「if」的出現次數,但退出循環後的結果始終爲0。問題是如何可能解決的。計算從C中的文本文件中出現的單詞的出現次數
#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;
}
如果一個句子包含單詞'cliff'會怎麼樣?這是否算作命中,因爲'懸崖'包含'如果'? – Brandin