Find character occurrences in a file c++

Could you please tell me, how to count the occurrence of each individual letter
(for example "d","c",....) in a given file that contain random letter sequence (for example" asjdjuendncnwjashdnd...") and display the answer as percentage (for example d found 10 times so it would be 15% of the file letters).
Thanks in advance.
you would use Standard template library classes to achive that task:
ifstream class to read a file for example.

this web site has nice tutorial on how to use STL classes.. just click on the link "Reference" here on the left upper corner.
My problem is that i don't know how to count the characters in the file. i manage to open the file and read from it but i don't know how to process the information in the file and find how many d for example are in the file.
http://www.cplusplus.com/reference/iostream/ifstream/

check functions peek and get to extract and get the char.
/*
1.sorry,I am not good at english. 希望下面的code对你有用。
2.统计infile.txt文件中每个letter及其出现的次数
3.example:
文件内容:
dog cat cat dog pig
pig dog deck monkey
goose goose pig
t t ttt ttt
输出:
a 2
c 3
d 4
e 4
g 8
i 3
k 2
m 1
n 1
o 8
p 3
s 2
t 10
y 1

sum = 52; //letter总数
*/

#include <string>
#include <map>
#include <fstream>
using namespace std;
int main()
{
map<char, int>myMap; //定义map容器
ifstream infile("infile.txt"); //打开文件流

char letter;
while( infile >> letter) // 将文件中内容读入letter
{
myMap[letter]++; //将文件中出现的letter以 <key value>的形式存储到myMap中
}

map<char,int>::const_iterator iter;
int sum = 0;
for( iter = myMap.begin(); iter != myMap.end(); ++iter)
{
cout << iter->first <<" " << iter->second << endl; //putout the “letter” 和它出现的次数
sum += iter->second; //计算letter总数
}

cout << sum << endl;

}
Last edited on
Topic archived. No new replies allowed.