Program to calculate frequency of letters in a text file

Hello, I'm trying to come up with a program that finds how many times each letter occurs in a text file, and then outputs the results on a screen.

I don't know where I'm going wrong. Also, is there a simpler program that will find the frequency of letters in a text file?

Any help would be greatly appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;


int main()
{
	int total[26] = { 0 };

	ifstream infile("cipher.txt");
	if (!infile)
	{
		cout << "Error opening cipher file" << endl;
		return 0;
	}

	char c;
	while (infile.get(c))         // read characters one at a time
	{
		if (isalpha(c))           // check it is a-z or A-Z
		{
			
			int index = c - 'A';  // index in range 0 to 25;

			total[index]++;       // increment corresponding total
		}
	}

	for (int i = 0; i<26; i++)      // Print the results
	{
		cout << "  " << char(i + 'A') << " occurs "
			<< setw(5) << total[i] << " times" << endl;
	}

	system("pause");
	return 0;
}
index isn't going to be in the range you think it'll be in. It might be arduous, but your best bet is a huge if/else block that assigns 0 to 'a' and 'A', 1 to 'b' and 'B', and so on. Your program is going to crash often because index will quite often have values outside the range 0-25.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cctype> // std::isalpha(), std::toupper()

int main()
{
        const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ;
	int total[26] = { 0 };

	std::ifstream infile( "cipher.txt" );
	if (!infile) { /* ... */ }

	char c;
	while( infile.get(c) ) // read characters one at a time
	{
		if( std::isalpha(c) ) // check it is a-z or A-Z
		{
			c = std::toupper(c) ; // convert lower case to upper case

			// get the index of the upper case letter
			int index = 0 ;
			while( alphabet[index] != c ) ++index ;

			// index in range 0 to 25;
			++ total[index] ; // increment corresponding total
		}
	}

	for( int i = 0; i<26; ++i ) // Print the results
	{
		std::cout << "  " << alphabet[i] << " occurs "
			       << std::setw(5) << total[i] << " times\n" ;
	}
}
First off it will help if you open the file in binary mode, otherwise any control characters might get all screwy. Second, if you're looking at a cipher that has mixed upper and lower case letters then chances are that those letters are completely different, in other words 'a' and 'A' are not the same letter being encoded. Thirdly why aren't you using std::count from the Algorithm header?: http://www.cplusplus.com/reference/algorithm/count/?kw=count
Thank you very much for the help.
Topic archived. No new replies allowed.