Letters in a text file

vegaseat 0 Tallied Votes 179 Views Share

Where you ever curious what the most common letter is in a typical text file? Just another question to ask a friend. The answer is right here in this tiny code snippet. The program converts the text to all lower case letters, and then list them out alphabetically showing the frequency.

// get one character at a time from a text file
// convert to lower case and count letters 'a' to 'z'
// a Dev-C++ tested console application by  vegaseat  30apr2005

#include <iostream>
#include <fstream>

using namespace std;

// count letters 'a' to 'z' in string s
void countLetters( string s )
{
  int pos, sum = 0;
  char m;
  
  // only a to z
  for( m = 97; m < 123; m++ )
  {
    // start with index = 0
    pos = s.find( m, 0 );
    while( pos != string::npos )
    {
      // adjust index up
      pos = s.find( m, pos+1 );
      // total up this character
      sum++;
    }
    if ( sum > 0)
    {
      cout << m << " = " << sum << endl;
    }
    sum = 0;
  }
}

int main()
{
  char c;
  string str1;
  ifstream is;

  // open this text file, or replace with a text file you have ...
  is.open("Microwave.txt");

  // loop while extraction from file is possible
  while ( is.good() ) {
    // get character from file
    c = is.get();
    cout << c;
    // build string with all lower case characters
    c = tolower( c );
    str1.push_back( c );
  }
  cout << endl << endl;
  cout << str1 << endl;
  // count letters a to z
  countLetters(str1);

  // close file
  is.close();
    
  cin.get(); // wait	
  return 0;
}
belka 0 Newbie Poster

How would I modify this to count how many are upper case, how many are lower case, how many are spaces, and how many carriage returns there are?

mattz 0 Newbie Poster

just use the asciii values..
.

programtrav 0 Newbie Poster

how would i find the top 5 most common letters in the file.And how to give the total number of occurences as well as the percentage of the total number of letters.Can you give code please.

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.