I'm trying to write a program which reads in a string of defined size from the keyboard and displays how many times each letter appears and also displays how many non-alphabetical characters appear.

So far, it successfully counts the number of letters. However, I'm really struggling with getting the string to work and I'm also unsure of how to count the non-alphabetical characters.

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

int Pos, CountArray[26];
char ch;
const int MAXSIZE = 10;

int main ()
{

	char line[MAXSIZE] = {'\0'};

	printf("Enter string: ");
	fgets(line, sizeof(line), stdin);
	line[strlen(line) - 1] = '\0';

	for(Pos=0;Pos<26;Pos++)
	{
	CountArray[Pos] = 0;
	}
	
	printf("Enter a sentence, ending with a fullstop: ");
	
	ch=getchar();
	while(ch != '.')
	{
		if(isalpha(ch))
		{
		ch = toupper(ch);
		CountArray[ch-'A']++;
	}
					
	ch = getchar ();
	}
	
	for(Pos=0;Pos<26;Pos++)
	{
	printf("%c=", Pos+'A');
	printf("%d: ", CountArray[Pos]);
	}
	
	return(0);

}

Recommended Answers

All 2 Replies

[edit]

You have the right idea already, just extend it for all characters instead of just the alphabet. Then you can either process the frequency array later to get the count of non-alphabetical characters, or keep a running count if you wish:

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

int main(void)
{
    int freq[UCHAR_MAX] = {0};
    int non_alpha = 0;
    int ch;

    while ((ch = getchar()) != EOF) {
        ++freq[ch];

        if (!isalpha(ch))
            ++non_alpha;
    }

    /* Display the table */

    return 0;
}
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.