题目
给定一英文文本文件data.dat,编写C++程序,读取文件中的内容,统计文件中出现次数最多的三个单词,并给出这三个单词的出现次数,同时输出程序运行的时间。(注: 这里不区分单词大小写,如, he 与 He 当做是同一个单词计数)
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
//#include <algorithm>
#include <conio.h>
#include <Windows.h>
using namespace std;
struct count
{
string word;
int num;
};
int main()
{
long t1 = GetTickCount();
vector<count> v;
count tempstr;
ifstream in("data.dat");
string temp; //缓冲区
string str;
int count=0;
int j=0;
while(getline(in,temp)) //文件读取结束时退出循环
{
//transform(temp.begin(), temp.end(), temp.begin(), tolower); // 转换为小写,头文件冲突?
for(int i=0; i<temp.length(); i++)
{
for(; i<temp.length(); i++)
{
if( (temp[i]>='a'&&temp[i]<='z') || (temp[i]>='A'&&temp[i]<='Z') )
{
temp[i]=tolower(temp[i]); //转换成小写
count++;
}else
break;
}
if(count)
{
str=temp.substr(i-count,count);
if(v.size())
{
for(j=0; j<v.size(); j++)
{
if(str.compare(v[j].word)==0)
{
v[j].num++;
count=0;
break;
}
}
}
if(j>=v.size())
{
tempstr.word = str;
tempstr.num = 1;
v.push_back(tempstr);
count=0;
}
}
}
}
int glass=0,n=v.size();
string glastr;
for(int i=0; i<3; i++)
{
for(int k=0; k<=n-2-i; k++)
{
if(v[k].num>v[k+1].num)
{
glass=v[k].num;
v[k].num=v[k+1].num;
v[k+1].num=glass;
glastr=v[k].word;
v[k].word=v[k+1].word;
v[k+1].word=glastr;
}
}
}
cout<<"出现次数前三:"<<endl;
for(int i=1; i<=3; i++)
{
cout<<v[n-i].word<<" 出现"<<v[n-i].num<<"次"<<endl;
}
long t2 = GetTickCount();
cout<<"totle time:"<<t2-t1<<"s"<<endl;
getch();
return 0;
}