LearnFrenzy
Sign in Take a free test

File Handling (fstream) · File Handling Programs · Question 2

Word frequency of a text file in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

Read a text file word by word, normalise each word (lower-case, strip punctuation), count frequencies in a std::map and write the top words to a report file; print the report.

Solution
main.cpp
#include <algorithm>
#include <cctype>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>

int main() {
    auto dir = std::filesystem::temp_directory_path();
    std::ofstream(dir / "lf_article.txt") << "C++ is fast. C++ is powerful!\nLearning C++ is fun, and fun is good.\n";

    std::map<std::string, int> freq;
    std::ifstream in(dir / "lf_article.txt");
    for (std::string w; in >> w; ) {
        std::string clean;
        for (unsigned char c : w) if (std::isalnum(c) || c == '+') clean += static_cast<char>(std::tolower(c));
        if (!clean.empty()) ++freq[clean];
    }

    std::vector<std::pair<std::string, int>> v(freq.begin(), freq.end());
    std::stable_sort(v.begin(), v.end(), [](const auto& a, const auto& b) { return a.second > b.second; });
    {
        std::ofstream report(dir / "lf_freq.txt");
        for (std::size_t i = 0; i < 4 && i < v.size(); ++i) report << v[i].first << ' ' << v[i].second << '\n';
    }
    std::ifstream report(dir / "lf_freq.txt");
    std::cout << report.rdbuf();
    report.close(); in.close();
    std::filesystem::remove(dir / "lf_article.txt");
    std::filesystem::remove(dir / "lf_freq.txt");
    return 0;
}

Output Verified by compiling and running

is 4
c++ 3
fun 2
and 1

Reading with >> gives raw words with punctuation attached, so each is cleaned first. stable_sort keeps alphabetical order among equal counts.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links