Hello, for the final part of my program I need to count how many letters appear throughout a pretty large input file. Opening the file, storing to an array, etc.. is all taken care of. I'm clueless on how to count each letter that occurs. I've read structures are the way to go, and others that arrays are best. I know I'd need to declare an array along the lines of:

char letters[26] = "abcdefghijklmnopqrstuvwxyz";

but I'm clueless from here, thanks in advance for any help, tips and/or suggestions.

Dani AI

Generated

Short summary and a safe pattern you can apply immediately. As noted, you want a fixed set of counters rather than trying to treat the alphabet as a string. As suggested, use the character value as an index. Ignore strlen for this task (as hinted) because files are streams and may contain NULs or be large — count as you read.

A compact, safe ASCII-only approach:

#include <stdio.h>
#include <stdint.h>

int main(void) {
    FILE *f = fopen("input.txt", "rb");
    if (!f) return 1;
    uint64_t counts[26] = {0};
    int ch;
    while ((ch = fgetc(f)) != EOF) {
        if (ch >= 'A' && ch <= 'Z')
            counts[ch - 'A']++;
        else if (ch >= 'a' && ch <= 'z')
            counts[ch - 'a']++;
    }
    fclose(f);
    for (int i = 0; i < 26; ++i)
        printf("%c: %llu\n", 'a' + i, (unsigned long long)counts[i]);
    return 0;
}

Notes, caveats and troubleshooting:

  • The explicit range checks above avoid locale and signed-char pitfalls. If you prefer isalpha/tolower, always cast to unsigned char before calling them to avoid undefined behavior on negative char values.
  • Use a 64-bit counter type (or size_t) for very large files so counts do not overflow.
  • For performance on huge files, fread into a buffer and scan the buffer is faster than fgetc.
  • If the input may be UTF-8 or contain non-ASCII letters, byte-wise checks are insufficient. Decode code points (mbrtowc/iswalpha or a Unicode library like ICU) and count by code point class instead.
  • If results look wrong: confirm the file opened successfully, verify you are checking the correct character ranges, and watch for signed/unsigned mistakes that produce negative indices.

Recommended Answers

All 2 Replies

An array of characters is a string, and therefore checking the various methods available for strings in c would probably be a good start. Google strlen and see if that's any help.

Each character (letter, number, punctuation) has a numeric value. That value can be used as an index into an array of counters which you can increment for each character you read.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.