//读取一个英文的文本文件,统计文本文件中的单词的词频,按照词频从大到小依次输出单词和词频。
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <fstream>
using namespace std;
map<string, int>countword;
int main()
{
ifstream in_file("C:\\english.txt", ios::in);
if (!in_file)
{
cerr << "打开文件失败!";
exit(-1);
}
string str,line;
while(getline(in_file, line))
{
istringstream word(line);
while (word >> str)
if (countword.find(str) == countword.end())
countword[str] = 1;
else
countword[str]++;
}
map<string, int>::iterator it = countword.begin();
for (; it != countword.end(); it++)
{
cout << it->first << ":" << it->second<<endl;
}
in_file.close();
return 0;
}
可改进:filename
string filename;
cout<<"请输入文件名:"<<endl;
cin>>filename;
ifstream in_file(filename;ios::in);
//头文件 #include <sstream> //关键代码 while(getline(in_file, line))//std::getline(iostream&,string)获取一行存入string中 { istringstream word(line); //isstreaming是一种输入流,可以将空格之间的内容提取出来 while (word >> str) //Word提取了string line,word输出str(str用于临时存取获得的空格之前的内容,用于输出) if (countword.find(str) == countword.end()) countword[str] = 1; else countword[str]++; //STL map查询key值是否存在 -> mymap.find(char*/string)若查到返回当前的迭代器,无则返回.end()的位置
学习参考:(28条消息) C++ ostringstream、istringstream、stringstream 用法浅析_HelloKandy的博客-CSDN博客