It seems as though you are trying to count how many times each alphabetical character appears in the input stream.
It appears you try to start with '`'
, because it comes one before 'a'
, as a way to build out an array that contains the alphabet. This is confusing.
This for
loop seems to be an attempt to read at most ten characters,
for (int f = 0; f < 10; ++f) {
while ((c[f] = getchar()) != EOF) {
but the while
loop attempts to read the entire input stream.
Note that the negative value of EOF
cannot be tested against properly if char
(the type of c[f]
) is unsigned on your system. Use int
when handling the return value of getchar
.
You have an unnecessary amount of nested loops. Use one loop to read the input. Use a separate loop to print the output.
With ASCII, 'a' - 'a'
is 0
, 'b' - 'a'
is 1
, and so on until 'z' - 'a'
is 25
. Use these values to index an array which keeps an individual count of each alphabetical character. Flip the operation to retrieve a character from an index (e.g., 'a' + 5
is 'f'
).
An example. Here we ignore non-alphabetic characters, and operate with case-insensitivity.
#include <ctype.h>
#include <stdio.h>
#define ALPHALEN 26
int main(void) {
unsigned counts[ALPHALEN] = { 0 };
int c;
while (EOF != (c = getchar()))
if (isalpha(c))
++counts[tolower(c) - 'a'];
for (int i = 0; i < ALPHALEN; i++)
printf("%c = %u\n", 'a' + i, counts[i]);
}
Alternatively, use fgets
to read lines of input.
#include <ctype.h>
#include <stdio.h>
#define ALPHALEN 26
void alphacount(const char *str) {
unsigned counts[ALPHALEN] = { 0 };
while (*str) {
unsigned char c = (unsigned char) *str++;
if (isalpha(c))
++counts[tolower(c) - 'a'];
}
for (int i = 0; i < ALPHALEN; i++)
printf("%c = %u\n", 'a' + i, counts[i]);
}
int main(void) {
char buffer[512];
while (1) {
printf(">> ");
if (!fgets(buffer, sizeof buffer, stdin))
break;
alphacount(buffer);
}
}