-
Notifications
You must be signed in to change notification settings - Fork 294
/
wordcount.cc
97 lines (87 loc) · 2.3 KB
/
wordcount.cc
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <map>
#include <vector>
#include <iterator>
#include <memory>
class word_counter;
class input_reader
{
private:
std::shared_ptr<word_counter> counter_;
public:
void set_counter(std::shared_ptr<word_counter> counter);
std::string next_filename();
};
class word_counter
{
private:
std::vector<std::string> words_;
bool done_ = false;
std::shared_ptr<input_reader> reader_;
public:
word_counter(std::shared_ptr<input_reader> reader);
bool done() const;
std::map<std::string, int> word_count();
};
void input_reader::set_counter(std::shared_ptr<word_counter> counter)
{
counter_ = counter;
}
std::string input_reader::next_filename()
{
std::string input;
std::cout << "filename or 'quit'> ";
std::getline(std::cin, input);
if (input == "quit")
return "";
return input;
}
word_counter::word_counter(std::shared_ptr<input_reader> reader) : reader_(reader)
{
}
bool word_counter::done() const
{
return done_;
}
std::map<std::string, int> word_counter::word_count()
{
std::string filename = reader_->next_filename();
if (filename == "")
{
done_ = true;
return {};
}
std::ifstream in(filename);
std::copy(std::istream_iterator<std::string>(in),
std::istream_iterator<std::string>(),
std::back_inserter(words_));
std::map<std::string, int> counts;
for (auto const& word: words_) {
auto it = counts.find(word);
if (it == counts.end())
counts[word] = 1;
else
it->second++;
}
return counts;
}
int main()
{
bool done = false;
while (!done)
{
auto reader = std::make_shared<input_reader>();
auto counter = std::make_shared<word_counter>(reader);
reader->set_counter(counter);
auto counts = counter->word_count();
done = counter->done();
for (auto const& wc : counts)
{
std::cout << wc.first << " " << wc.second << '\n';
}
}
return 0;
}