C++: Letter Frequency

Bjarne-stroustrup
 


Open a text file and count the occurrences of each letter.

Some of these programs count all characters (including punctuation), but some only count letters A to Z.

#include <fstream>
#include <iostream>
 
int main()
{
	std::ifstream input("filename.txt", std::ios_base::binary);
	if (!input)
	{
		std::cerr << "error: can't open file\n";
		return -1;
	}
 
	size_t count[256];
	std::fill_n(count, 256, 0);
 
	for (char c; input.get(c); ++count[uint8_t(c)]) // process input file
		; // empty loop body
 
	for (size_t i = 0; i < 256; ++i)
	{
		if (count[i] && isgraph(i)) // non-zero counts of printable characters
		{
			std::cout << char(i) << " = " << count[i] << '\n';
		}
	}
}
Output:

when file contains “Hello, world!” (without quotes):

! = 1
, = 1
H = 1
d = 1
e = 1
l = 3
o = 2
r = 1
w = 1

SOURCE

Content is available under GNU Free Documentation License 1.2.