Thread: Finding the most common char

  1. #1
    Registered User
    Join Date
    Feb 2002
    Posts
    37

    Finding the most common char

    How do I find out the most common char and how often it occurs in a textfile?

    ////////////////////////////////////////////////////////////////////////////////////
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>       
    #include <stdbool.h>             
    
    int main()
    {
       char c;              
       int up_ct = 0;   
       int low_ct = 0;
       int dig_ct = 0;               
       int n_words = 0;     
       int punc_ct = 0;     
       int rows = 1;
       int total = 0;
       bool inword = false;
       FILE *fp;
    
       fp = fopen("e:\\test.txt", "r");
    
       while ((c = getc(fp)) != EOF)
       {
            if (islower(c))
               low_ct++;
            else if (isupper(c))
               up_ct++;
            else if (isdigit(c))
               dig_ct++;
            else if (ispunct(c))
               punc_ct++;
            else if ('\n' == c)
               rows++;
               
          if (!isspace(c) && !inword)
          {
             inword = true;  
             n_words++;                
          }
          
          if (isspace(c) && inword)
             inword = false; 
       }
       
       total = up_ct + low_ct + dig_ct;
       
       printf("\nwords = %d, totalchar = %d, lowercase = %d, uppercase = %d "
              "digits = %d, punctuation = %d, rows = %d",
               n_words, total, low_ct, up_ct, dig_ct, punc_ct, rows);
              
       fclose(fp);
       return 0;
    }

  2. #2
    Registered User
    Join Date
    Oct 2002
    Posts
    98
    A blunt way of doing this would be to create an array of integers to represent each character, then switch after each getc, and increment the integer representing that letter.

    int *n;

    n = (int *) malloc( sizeof( int ) * ( 'z'-'A'));

    c = getc(fp)....

    switch( c )
    {
    case('a'): n['a' - 'A']++;
    break;
    .
    .
    .
    }

    I may have the letters the wrong way round (I can't remember whether 'A' or 'a' comes first in the ascii listing, and I can't get to a compiler at the moment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  2. Sorting Linked Lists
    By DKING89 in forum C Programming
    Replies: 6
    Last Post: 04-09-2008, 07:36 AM
  3. need help finding problems
    By kwm32 in forum C++ Programming
    Replies: 1
    Last Post: 08-22-2004, 05:49 PM
  4. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 11:58 AM
  5. I'm having a problem with data files.
    By OmniMirror in forum C Programming
    Replies: 4
    Last Post: 05-14-2003, 09:40 PM