C语言读取文件统计字母个数

读取文件中的字符串,统计a到z字母各自出现的次数,并将结果放入数组中。如文件中有字符串abcdefgabcddanc,输出33322110000000000000000000。
#include<stdio.h>
#include<stdlib.h>
main(void){
FILE *fp;
int i,length,count[26];
char ch,ch1[100];
if((fp=fopen("21letters.txt","r"))==NULL){
printf("Can't open the file.\n");
exit(1);
}
while((ch=fgetc(fp))!=EOF){
for(i=0;i<26;i++){
if(ch=='a'+i){
count[i]++;
}
}
}
for(i=0;i<26;i++){
printf("%d ",count[i]);
}
if(0!=fclose(fp)){
printf("Can't close the file.\n");
exit(1);
}
return 0;
}

img

img


为什么输出结果是这样

帮你改了下

#include<stdio.h>
#include<stdlib.h>
main(void)
{
    FILE *fp;
    int i,length,count[26]={0};
    char ch,ch1[100];
    if((fp=fopen("21letters.txt","r"))==NULL)
    {
        printf("Can't open the file.\n");
        exit(1);
    }
    while((ch=fgetc(fp))!=EOF)
    {
        {
            printf("%c ",ch);
            if('a'<=ch&&ch<='z')
            {
                count[ch-97]++;
            }
            if('A'<=ch&&ch<='Z')
            {
                count[ch-65]++;
            }
        }
    }
    for(i=0; i<26; i++)
    {
        printf("%d ",count[i]);
    }
    if(0!=fclose(fp))
    {
        printf("Can't close the file.\n");
        exit(1);
    }
    return 0;
}


#include<stdio.h>
#include<stdlib.h>
int main(void) {
    FILE* fp;
    int i, length, count[26] = {0};
    char ch, ch1[100];
    if ((fp = fopen("21letters.txt", "r")) == NULL) {
        printf("Can't open the file.\n");
        exit(1);
    }
    while ((ch = fgetc(fp)) != EOF) {
        count[ch - 'a']++;
        //for (i = 0; i < 26; i++) {
        //    if (ch == 'a' + i) {
        //        count[i]++;
        //    }
        //}
    }
    for (i = 0; i < 26; i++) {
        printf("%d ", count[i]);
    }
    if (0 != fclose(fp)) {
        printf("Can't close the file.\n");
        exit(1);
    }
    return 0;
}