Chinaunix首页 | 论坛 | 博客
  • 博客访问: 160057
  • 博文数量: 30
  • 博客积分: 2010
  • 博客等级: 大尉
  • 技术积分: 290
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-25 19:05
文章分类

全部博文(30)

文章存档

2009年(3)

2008年(27)

我的朋友

分类: C/C++

2008-11-27 15:28:08

以下程序实现:从1.txt中读入英文句子,统计每个单词出现的频率,按照字典顺序输出。

知识点:关联容器map

 

#include<iostream>
#include<string>
#include<fstream>
#include <algorithm>
#include<map>
using namespace std;
ifstream & open_file(ifstream& in, const string& name){
       in.close();
       in.clear();
       in.open(name.c_str());
       return in;
}
int main(){
       map<string, int> word_count;
       ifstream if1;
       if(!open_file(if1,"1.txt")){cout<<"open file 1.txt failed!"<<endl; return 0;}
       string word;
       while (if1>>word){
              transform(word.begin(),word.end(),word.begin(),tolower); 
              ++word_count[word];
       }
       map<string, int>::iterator map_it=word_count.begin();
       while (map_it!=word_count.end()){
              cout<<map_it->first<<":"<<map_it->second<<endl;
              ++map_it;
       } 
       return 0;
}

阅读(759) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~