-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathword_counter.cpp
54 lines (47 loc) · 1.31 KB
/
word_counter.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include "word_counter.h"
#include <string>
#include <fstream>
#include <algorithm>
word_counter::word_counter() {
all = 0;
}
using namespace std;
string GetWord(istream& in) {
char symbol;
string ans = "";
symbol = in.get();
while (!isalpha(symbol) && !in.eof()) {
symbol = in.get();
}
while (isalpha(symbol)) {
ans.push_back(symbol);
symbol = in.get();
}
return ans;
}
void word_counter::opentxt(const string& fileName) {
ifstream input(fileName);
if (!input) {
cout << "Input file error";
}
string word;
while (!(word = GetWord(input)).empty()) {
++wordMap[word];
++all;
}
}
void word_counter::createcsv(const std::string& fileName) {
multimap<int, string> sortedWordMap;
for (auto word = wordMap.rbegin(); word != wordMap.rend(); ++word) {
sortedWordMap.insert(pair<int, string>(word->second, word->first));
}
wordMap.clear();
ofstream out(fileName);
if (!out) {
cout << "Output file error";
}
for (auto element = sortedWordMap.rbegin(); element != sortedWordMap.rend(); ++element) {
out << element->second << ',' << element->first << ',' << element->first / (double)all * 100 << '%'
<< endl;
}
}