2016-10-12 36 views
0

我有一個應該計算一個字母出現在文本文件中的次數的程序。與計數器和文件輸入/輸出的交互

void file_histogram(char *filename) 
{ 
    FILE *file1; 
    file1 = fopen(filename, "r"); 
    int size = 26; 
    int charCounters[size]; 
    char c; 
    int i, j; 

    if(file1 != NULL) { 
     while(fscanf(file1, "%c", &c) == 1) { 
      for(i = 0; i < size; ++i) { 
       if(c == i + 97) { 
        charCounters[i]++; 
        break; 
       } 
      } 
     } 
    } 
    for(j = 0; j < size; ++j) 
     printf("%c: %d\n", j + 97, charCounters[j]); 
    fclose(file1); 

這是什麼似乎是在做兩次計數的第一個字符,然後大約有一半是正確計數,而另一半似乎都達到最大或溢出。這裏究竟發生了什麼?

+0

你如何確定int size = 26?這是應該爲一個特定的「已知」文件或任何文件? – inbinder

+2

a)您從未將charCounters設置爲全部0. b)爲什麼您甚至在該文件閱讀部分中有for循環? – John3136

+0

該數組是針對字母表的每個字母 – nichow

回答

0

第一個for()循環的邏輯不正確。建議像這樣:

#include <ctype.h> 
.... 
// initialize to all 0s 
int charCounters[26] = {0}; 
.... 
while(fscanf(file1, "%c", &c) == 1) 
{ 
    if(isalpha(c)) 
    { // then alphabet a...z or A...Z 
     // -'a' to get offset from lower case 'a' 
     // to use as index into array 
     charCounters[ tolower(c)-'a' ]++; 
    } 
}