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.
Letters in a text file
// 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;
}
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.