-
Help! Please
I'm trying to write a program to count the number of each letter of the alphabet and count the words. I have the word count but don't know how to start my letter counts.
thanks in advance for your help...
Here is what i have so far:
# include <iostream.h>
# include "string.h"
void alphabet( char [] ); //functions prototype
int main()
{
int count = 0;
char string[256];
cout <<"Please enter 1 line of text from the keyboard. \n";
cout <<"Please hit enter when you are done.\n\n";
cin.getline(string, 256, '\n'); //The user input goes into string
int countA = 0;
for(int i = 0; i < 256; i++)
{
if (string[i] == 'a' || 'A')
countA++;
else
}
cout <<"A " << countA << "\n";
char *tokenPtr;
tokenPtr = strtok( string, " " );
while ( tokenPtr != NULL )/* The following code counts the words or tokens in a sentence.*/
{
tokenPtr = strtok( NULL, " " );
count = count + 1;
}//end while ( tokenPtr != NULL )
cout << "Word Count: " << count;
return 0;
}//end int main ()
-
You could create a 26 element array 0-a 25-z, and loop through your line incremeting the [theletter-a] element for each letter.
-
this will get you started
Code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int Occurences( char cAlpha, char* szString );
int main()
{
char szString[ 256 ];
strcpy( szString, "THis is a very long STRING and all characters WILL BE counted" );
char cAlpha = 'A';
for( int i = 0; i < 26;i++ )
{
cout << cAlpha << " occurs " << Occurences( cAlpha , szString )
<< " times in the string \"" << szString << "\""<< endl;
cAlpha++; // a + 1 = b and so on
}
return 0;
} // end
int Occurences( char cAlpha, char* szString )
{
// NULL pointer bad ju-ju
if( NULL == szString )
{
return 0;
}
int i = 0;
int nCount = 0;
do
{
//an Uppercase character + 32 is the lowercase of the character
//here we test for both.. more info on this look at an acii code chart
if( cAlpha == szString[ i ] || ( cAlpha + 32 ) == szString[ i ] )
nCount++;
i++;
}
while( NULL != szString[ i ] );
return nCount;
}
-
I still don't get it, i want it so the user can enter a line of text.