1
/**/
/*
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : CountRepeaterByWordByMap.cpp
5Compiler : Visual C++ 8.0
6Description : Demo how to count repeated words by std::map
7Release : 11/16/2006
8*/
9
10 #include < iostream >
11 #include < fstream >
12 #include < cctype >
13 #include < string >
14 #include < map >
15 #include < algorithm >
16
17 void repeatedWords(std:: string );
18
19 int main() {
20 std::string fileName("textfile.txt");
21 repeatedWords(fileName);
22
23 return 0;
24}
25
26 void repeatedWords(std:: string fileName) {
27
28 std::ifstream infile(fileName.c_str());
29
30 if (!infile) {
31 std::cout << "Read error!!" << std::endl;
32
33 return;
34 }
35
36 std::map<std::string, int> wordCount;
37 for(std::string word, newWord; infile >> word; ++wordCount[newWord], newWord="") {
38 for(std::string::iterator iter = word.begin(); iter != word.end(); ++iter) {
39 if (!ispunct(*iter)) {
40 newWord.push_back(tolower(*iter));
41 }
42 }
43 }
44
45 infile.close();
46
47 // cout the result
48 for(std::map<std::string, int>::iterator iter = wordCount.begin();
49 iter != wordCount.end(); ++iter) {
50 std::cout << "The Word '" << iter->first << "' Occurrence:" << iter->second << " times" << std::endl;
51 }
52}
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : CountRepeaterByWordByMap.cpp
5Compiler : Visual C++ 8.0
6Description : Demo how to count repeated words by std::map
7Release : 11/16/2006
8*/
9
10 #include < iostream >
11 #include < fstream >
12 #include < cctype >
13 #include < string >
14 #include < map >
15 #include < algorithm >
16
17 void repeatedWords(std:: string );
18
19 int main() {
20 std::string fileName("textfile.txt");
21 repeatedWords(fileName);
22
23 return 0;
24}
25
26 void repeatedWords(std:: string fileName) {
27
28 std::ifstream infile(fileName.c_str());
29
30 if (!infile) {
31 std::cout << "Read error!!" << std::endl;
32
33 return;
34 }
35
36 std::map<std::string, int> wordCount;
37 for(std::string word, newWord; infile >> word; ++wordCount[newWord], newWord="") {
38 for(std::string::iterator iter = word.begin(); iter != word.end(); ++iter) {
39 if (!ispunct(*iter)) {
40 newWord.push_back(tolower(*iter));
41 }
42 }
43 }
44
45 infile.close();
46
47 // cout the result
48 for(std::map<std::string, int>::iterator iter = wordCount.begin();
49 iter != wordCount.end(); ++iter) {
50 std::cout << "The Word '" << iter->first << "' Occurrence:" << iter->second << " times" << std::endl;
51 }
52}