Saturday, 3 December 2016

Write a program to count characters from a file


#include <stdio.h>
#include <varargs.h>
#include <ctype.h>

....................

        c = toupper(c);

        if (c == 'A')
            alphabet[0]++;


    printf("Letter Frequency\n\n");
    for (i = 0; i < 26; i++)
    {
        printf("%c %d\n", (char)(i+'A'), alphabet[i]);
    }
}
What I'm having trouble with, is counting all the different letters and having this carry over to the output of the file.
When I comment out this line: c = toupper(c); it seems to work well but for A only. I would rather have a way of doing all the letters automatically rather than typing A to Z. What am I doing wrong?
--------------------------------------------------------------------------------------------------------------------------

Answers;

Look closely at your loop. There are no braces after the while, so the body only contains the line c = toupper(c);. You need to add braces to add the if block to the loop as well.
To update the array, subtract the character in question from 'A'. You're doing the opposite when you print, so I'm surprised you didn't think of this. This will give you the index in the array.
while ((c= getc(fptr)) != EOF) {
    c = toupper(c);
    if (c >= 'A' && c <= 'Z') {
        alphabet[c - 'A']++;
    }
}



No comments:

Post a Comment