-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathWordCounter.cpp
More file actions
59 lines (52 loc) · 914 Bytes
/
WordCounter.cpp
File metadata and controls
59 lines (52 loc) · 914 Bytes
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
#include "WordCounter.h"
bool WordCounter::loadFile(string filename)
{
ifstream ifs;
ifs.open(filename);
if(!ifs.is_open())
return false;
string line;
while(getline(ifs, line))
{
if(ifs.bad() || ifs.fail())
{
reset();
return false;
}
string word = "";
string::iterator it;
for(it=line.begin(); it != line.end(); ++it)
{
char c = *it;
if(c == ' ' || c == '\n' || c == '-')
{
if(word != "")
addWordToMap(word);
word = "";
}
else if(isalpha(c))
{
word += c;
}
}
if(word != "")
addWordToMap(word);
}
ifs.close();
return true;
}
void WordCounter::reset()
{
map.clear();
}
string WordCounter::toString() const
{
return map.toSortedString();
}
void WordCounter::addWordToMap(string word)
{
if(map.contains(word))
map[word]++;
else
map[word]=1;
}