Wednesday, 8 April 2009

A Word and Letter Counter program example

This is a very simple program but people can sometime get lost in writing them. I have not taken into account all the different error scenarios but this program is quite robust.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//In this program we will count the total number of words, letters
//and the frequency of each letter. For simplicity we will end the
//program when enter is pressed.
#include<iostream>

using namespace
std;

void
wordLetterCounter(int &numWords, int &numLetters, int letterCount[]);

int
main()
{

int
numWords = 0, numLetters = 0;
int
letterCount[26]={0}; //each letter count init to 0

cout<<"\n\nPlease enter some words and finish by pressing enter : ";

wordLetterCounter(numWords, numLetters, letterCount);

cout<<"\n\nNumber of Words = "<<numWords<<" Number of Letters = "<<numLetters<<endl;
cout<<"\nFrequency of letters as follows:"<<endl;
for
(int i = 0; i < 26; i++)
{

cout<<char('a'+i)<<" = "<<letterCount[i]<<endl;
}


return
0;
}


void
wordLetterCounter(int &numWords, int &numLetters, int letterCount[])
{

char
c;
char
lastLetter=' ';

//Remember 'A'=65, 'Z'=90 and 'a'=97, 'z'=122 in Ascii
while(cin.get(c))
{

//Converting upper to lower case to make it case insensitive
if(c >= 'A' && c <= 'Z')
c+=char(32);

//Increase Letter Count and number of letters
if(c >= 'a' && c <= 'z')
{

letterCount[c - 'a']++;
numLetters++;
}


//Increase number of words
if(c == ' ' && lastLetter != ' ')
numWords++;

//If new line then break;
if(c == '\n')
{

//Before you exit, the numWords should be increased if there was atleast 1 letter
if(numLetters)
numWords++;
break
;
}

lastLetter = c;
}
}




The Output is as follows. Note that there is a '.' and many spaces between Dr. and Spock but the wordcount is correct.

No comments:

Post a Comment