以下程序实现:从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; }
|
阅读(785) | 评论(0) | 转发(0) |