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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!