Hi..
Could anyone help me to find out why this program cannot count the frequency of each alphabet? There is a output for calculating the total lines and length but not the frequency.Appreciate any help. Thanks!

int main()
{
	const int MAXLENGTH=10;
	const int MAXCHARS=10000;
	static double i[26];
	char filename[MAXLENGTH]="ex.txt";
	char descrip[MAXCHARS];
        string lineBuffer;
        int length=0; 
	int lineCount = 1;
	char str2[26]= {'A','B','C', 'D', 'E', 'F', 'G', 'H', 'I','J', 'K', 'L', 'M', 'N','O', 'P', 'Q', 'R', 'S', 'T','U', 'V', 'W','X' ,' Y','Z'};
	int ch,count,z,q;
	ifstream infile;


	infile.open(filename, ios::in);

	if(infile.fail())
	{
		cout<<"The file was not successfully opened"<<endl;
		getch();
		exit(1);
	}

	
	while(!infile.eof())
	 {
       	        getline(infile, lineBuffer);	
		int count = 1;                  
                count = lineCount;
                                             
                cout << "\nThe line now are : " << count << endl;
		lineCount ++;    

		
		length = lineBuffer.length();      	      
		cout << "The length of line are : " << length << endl;	  	
               
		for(z = 0; z < count; z++) 
		{
		   for(q=0; q < 27 ; q++)
			{
				if( descrip[z]== str2[q])				
				i[q]++;				
			}   
		}

		for(q=0; q < 26; q++)
		{
			double g;

		  	g=i[q]/count;
			cout<<g<<endl;
		}
	}
	infile.close();
	cout<<endl;

	getch();
	return 0;
}

There are at least a couple ways to do it. One is using <map> class and the other is to use an array.

To use an array: create an int array of 255 elements, one for each possible char in the ascii character set. I know that's too many for the characters that will appear in a file but it makes the calculations easier and quicker. Next just increment the element of that array that corresponds to the character read from thje file.

Example:

int counts[255] = {0}; // initialize array with all 0s
char c = 'A'; // a character read from the file
counts[c]++; // increment

After you have finished with all the characters, you can print out a frequency count in alphabetical order by printing all the elements of the array that have a value greater than 0.

Can you please explain more or show me the code on how to work on it. I'm a newbie for c++. So I'm kinda stuck here. Your help are appreciated so much.

Use the character read from the file as an index into the array The Dragon mentions, and increment that value. Then when done, look through that array using an index and if the element is > 0, output the index as a character.

The Dragon already gave you the code.

This article has been dead for over six months. Start a new discussion instead.