Skip to content

Instantly share code, notes, and snippets.

@vlaleli
Created December 10, 2025 12:08
Show Gist options
  • Select an option

  • Save vlaleli/9f114fdc6284fd4d63e348ee19b973ac to your computer and use it in GitHub Desktop.

Select an option

Save vlaleli/9f114fdc6284fd4d63e348ee19b973ac to your computer and use it in GitHub Desktop.
#include <iostream>
#include "word_counter.h"
using namespace std;
int main() {
WordCounter wc;
wc.readFromFile("input.txt");
wc.printAll();
wc.printMostFrequent();
wc.writeToFile("output.txt");
return 0;
}
#include "word_counter.h"
#include <iostream>
#include <fstream>
#include <cctype>
using namespace std;
static string normalize(const string& s) {
string result;
for (char c : s) {
if (isalpha((unsigned char)c))
result += tolower(c);
}
return result;
}
void WordCounter::readFromFile(const string& filename) {
ifstream file(filename);
if (!file.is_open()) {
cout << "Ошибка открытия файла!" << endl;
return;
}
string word;
while (file >> word) {
string clean = normalize(word);
if (!clean.empty())
freq[clean]++;
}
file.close();
}
void WordCounter::printAll() const {
cout << "Все слова и их частоты:" << endl;
for (const auto& p : freq) {
cout << p.first << " : " << p.second << endl;
}
}
void WordCounter::printMostFrequent() const {
if (freq.empty()) {
cout << "Нет слов." << endl;
return;
}
string maxWord;
int maxCount = 0;
for (const auto& p : freq) {
if (p.second > maxCount) {
maxCount = p.second;
maxWord = p.first;
}
}
cout << "Самое частое слово: "
<< maxWord
<< " (" << maxCount << " раз)" << endl;
}
void WordCounter::writeToFile(const string& filename) const {
ofstream out(filename);
if (!out.is_open()) {
cout << "Ошибка записи файла!" << endl;
return;
}
out << "Результат подсчёта слов:\n";
for (const auto& p : freq) {
out << p.first << " : " << p.second << "\n";
}
string maxWord;
int maxCount = 0;
for (const auto& p : freq) {
if (p.second > maxCount) {
maxCount = p.second;
maxWord = p.first;
}
}
out << "\nСамое частое слово: "
<< maxWord
<< " (" << maxCount << " раз)\n";
out.close();
}
#pragma once
#include <map>
#include <string>
class WordCounter {
private:
std::map<std::string, int> freq;
public:
void readFromFile(const std::string& filename);
void printAll() const;
void printMostFrequent() const;
void writeToFile(const std::string& filename) const;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment