写一个程序,分析一个文本文件中各个词出现的频率。文本文件大约是30KB~300KB大小。
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class word
{
public:
string name;
int num;
word(){num=0;name="";};
};
void readfile(word*&inchar,int &counter)//read file word.txt
{
ifstream infile("E:\\word.txt");
if(!infile) {cout<<"cannot open!"<<endl;return;}
while(infile)
{
string temp;
infile>>temp;
int i=0;
for( ;i<counter;i++)
{
if(temp==inchar[i].name) { inchar[i].num++;break;}
}
if(i==counter&&inchar[i].name!=temp)
{
inchar[counter].name=temp;
inchar[counter].num++;
counter++;
}
};
infile.close();
}
void outfile(word*inchar,int counter)//output file out.txt
{
ofstream outfile("E:\\out.txt");
for(int i=0;i<counter;i++)
outfile<<"Word:"<<inchar[i].name<<endl<<"Time:"<<inchar[i].num<<endl;
}
void main()
{
word*inchar=new word[10000];
int counter=0;
readfile(inchar,counter);
outfile(inchar,counter);
}
图1:代码与输如输出文件图
图2:文件内容与输出内容节选
图2:VS2012中的PERFORMANCE ANALYSIS TOOL