Необходимо найти частоту появления в тексте символа и вывести с помощью контейнера map
Вроде как программу написал, но почему то частота везде равняется нулю, не могу понять в чем ошибка. Скорее всего ошибка в использовании функции count
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <map>
#include <locale>
using namespace std;
void main()
{
/*ЧТЕНИЕ ФАЙЛА*/
fstream in("text.txt");
string text;
string tmp;
while (!in.eof())
{
getline(in, tmp);
text += tmp;
}
ofstream out;
/*ЧТЕНИ ФАЙЛА ЗАВЕРШЕНО*/
/*ПРИВЕДЕНИЕ ТЕКСТА К ВЕРХНЕМУ РЕГИСТРУ*/
transform(text.begin(), text.end(), text.begin(), toupper);
map<unsigned char, double> letterFrequency;
int countOfSymbols = 0;
for (size_t i = 0; i < text.size(); i++)
{
if (isalpha((unsigned char) text[i]))
{
countOfSymbols++;
}
}
for (int i = 65; i <= 90; i++)
{
letterFrequency.insert(make_pair((unsigned char)i, count(text.begin(),
text.end(), (unsigned char)i) / countOfSymbols));
}
for (map<unsigned char, double>::iterator it =
letterFrequency.begin(); it != letterFrequency.end(); it++)
{
cout << it->first << " " << it->second << endl;
}
}
Ответы (1 шт):
Автор решения: Harry
→ Ссылка
Ну... зачем просто, если можно сложно? :)
int main()
{
ifstream in("text.txt");
char c;
map<char,int> m;
int total = 0;
while(in >> c) { m[toupper(c)]++; total++; }
for(auto k: m)
cout << k.first << " " << double(k.second)*100/total << "%\n";
}
Если надо считать и пробелы - то добавьте in >> noskipws; перед циклом чтения.
И еще - вот так
while (!in.eof())