I made a simple program for my study that calculates words in a text file and prints every word and its repeated times in the file.
How can I improve this code?
#include <future>
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
typedef std::unordered_map<std::string, std::size_t> Words;
Words wordsInFile(const std::string& fileName)
{
std::ifstream file(fileName);
if (!file.is_open())
{
throw "Can't open the file" + fileName;
}
Words loadFromFile;
for (std::string word; file >> word;)
{
++loadFromFile[word];
}
return loadFromFile;
}
int main(int argc, char *argv[])
{
std::vector<std::future<Words>> futures;
for (int i = 1; i < argc; ++i)
{
futures.push_back(std::async([=] { return wordsInFile(argv[i]); }));
}
Words words;
for (auto& i : futures)
{
const auto results = i.get();
for (const auto& j : results)
{
words[j.first] = j.second;
}
}
std::cout << "Word\tRepeated Times\n-------------------------\n";
for (const auto& i : words)
std::cout << i.first << "\t\t" << i.second << '\n';
}
test.txt
File system is huge subject need more work out. file is plain text file This is some junk words. simple program for words counting in text file. 1 2 3 2 2 2 2 @ % & ^ * all so good this test text file
Output:
Word Repeated Times ------------------------- File 1 out. 1 1 1 system 1 2 5 is 3 need 1 huge 1 subject 1 work 1 more 1 % 1 file 3 plain 1 text 3 This 1 some 1 junk 1 program 1 words. 1 simple 1 for 1 words 1 counting 1 in 1 file. 1 so 1 3 1 @ 1 & 1 ^ 1 this 1 * 1 all 1 good 1 test 1