2014-01-13 54 views
-1

以下代碼旨在從用戶選擇的文本文件中查找單詞「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; 
} 
+0

如果一個句子包含單詞'cliff'會怎麼樣?這是否算作命中,因爲'懸崖'包含'如果'? – Brandin

回答

2

如果測試是錯誤的。

if (read[i]=='if') /* no */ 

使用strcmp

if (strcmp(read[i], "if") == 0) /* check if the strings are equal */ 
+0

很好,工作。謝謝你的回答! (fscanf(f,「%s」,&next)!= EOF){if(strcmp(read,「if」)== 0) count ++; **也許我沒有不要正確使用for循環。 – user3140854

3
  1. 'if'是不是你認爲它是;它是一個多字符文字,而不是一個字符串。

  2. 您不能與C中的==進行比較。使用strcmp(3)

  3. 你的循環看起來並不像你想要的那樣;時間打破調試器(可能strtok(3))。

+0

也不需要寫'buf [strlen(buf)-1] ='\ 0';'。 – haccks

+0

沒有它似乎不能正常工作。 – user3140854

+0

爲什麼?我不這麼認爲。 – haccks

0

一方面,read[i]只包含一個字符,並且將永遠不等於任何多字符單詞。

另外,單撇號用於定義單個字符。 'if'不是一串字符。

您需要解析每一行以找到每個單詞,然後使用諸如stricmp()之類的內容將每個單詞與目標單詞進行比較。

相關問題