thG
thG

Reputation: 27

Storing counts of letters in an array

I am required to create a program that reads a file and store counts of all the letters, treating uppercase and lowercase letters the same. So far I got this:

FILE *input;  
int letter=0;
char words;
int typeofletter[letter];
input = fopen("greatgatsby.txt", "r");
while(fscanf(input, "%c", &words) != EOF)
{
    if ((words>='A')&&(words<='z'))
    {
       letter++;
    }
}

How would I store the count of each letter into an array?

Upvotes: 1

Views: 2200

Answers (4)

R Sahu
R Sahu

Reputation: 206687

  1. Create an array of size 26 to store the data.

    int lettercount[26] = {0};
    
  2. You can read the contents of the file character by character. Increment the letter count when you find a letter of the alphabet.

    int c;
    while ( (c = fgetc(input)) != EOF )
    {
      if ( isalpha(c) )
      {
        ++(lettercount[tolower(c)-'a']);
      }
    }
    

Upvotes: 2

Emmet
Emmet

Reputation: 6421

You should use the functions/macros in ctype.h to diagnose and convert characters. Below, isalpha() is used to tell if a character is a letter or not, and toupper() is used to convert a lowercase letter to an uppercase letter.

Since letters in ASCII (assumed) are represented by contiguous numbers, subtracting the value of 'A' from any uppercase letter (or 'a' from any lowercase letter) will give a value between 0 and 25 which corresponds to that letter and can be used as an index into an array of letter counts.

If your character set is not ASCII, this becomes considerably more difficult and beyond the scope of simple programming examples.

The following is a complete working example.

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

#define N_LETTERS (26)

int main(int argc, char *argv[])
{
    FILE *fp;
    int counts[N_LETTERS] = {0};
    int inchar;
    int i;

    /* We expect a filename on the command line */
    if(argc!=2) {
        fprintf(stderr, "Supply a filename as an argument.\n");
        exit(EXIT_FAILURE);
    }

    /* Open the file, bug out on error. */
    fp = fopen(argv[1], "r");
    if( fp==NULL ) {
        fprintf(stderr, "Failed to open file '%s'.\n", argv[1]);
        exit(EXIT_FAILURE);
    }

    /* This is the part you're most interested in */
    while( (inchar = fgetc(fp)) != -1 ) {  /* Read chars until error or EOF */
        if( isalpha(inchar) ) {            /* Only count letters            */
            i = toupper(inchar) - 'A';     /* Convert letter to index 0-25  */
            counts[i]++;                   /* Increment count for letter    */
        }
    }

    /* Close the file */
    fclose(fp);

    /* Print out the results */
    for(i=0; i<N_LETTERS; i++) {
        printf("Count of letter '%c': %d\n", 'A'+i, counts[i]);
    }

    return EXIT_SUCCESS;
}

Upvotes: 1

Jabberwocky
Jabberwocky

Reputation: 50831

You need probably this (quick and dirty, based on your version, no error checking, file not closed, not tested)

FILE *input;  
int letter=0;
char words;
int typeofletter[26];
input = fopen("greatgatsby.txt", "r");

while(fscanf(input, "%c", &words) != EOF)
{
   if ((words >= 'a') && (words <= 'z'))
   {
      words -= 'a'-'A' ;   // convert to up upper case
   }

   if ((words >= 'A') && (words <= 'Z'))
   {
      typeofletter[word - 'A']++;
   }
}

Upvotes: 1

VariableDeclared
VariableDeclared

Reputation: 23

The only issue I have to point out is that Arrays are statically set and their size is set, it cannot be changed dynamically.

You'd be better using another sequential container type such as c++ vector. For example:

int Main(int argc, char * argc[])
{
 //.... preceding code
 FILE * OpenedFile; //Get the file and open it
 vector<char> ChrVec;

 for(/*EACH LETTER*/)
 {
   ChrVec.push_back(/*LETTERPOINTER*/ *p);
 }
}

Upvotes: -3

Related Questions