如何统计出一篇文章出现的文字个数? (高级) (使用std::map)

 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
17void repeatedWords(std::string);
18
19int main() {
20  std::string fileName("textfile.txt");
21  repeatedWords(fileName);
22
23  return 0;
24}

25
26void 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::stringint> 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::stringint>::iterator iter = wordCount.begin();
49    iter != wordCount.end(); ++iter) {
50      std::cout << "The Word '" << iter->first << "' Occurrence:" << iter->second << " times" << std::endl;
51  }

52}

posted on 2006-11-16 12:39  真 OO无双  阅读(623)  评论(0)    收藏  举报

导航