之前有一个需求:统计一个混合中英文字符和各种符号的文件的各字符数量,结果发现,事情并没有想象的那么简单.于是先写个只统计英文字符的程序吧.
//data.txt需要放在相同目录下
//只能计算纯英文文件中的字符.
#include <iostream>
#include <map>
#include <fstream>
#include <algorithm>
#include <string>
#include <ctime>
#include <iomanip>
using namespace std;
int main(){
ifstream infile("data.txt");
string s1;
char c;
map<char,int> m1;
multimap<double,char> m2;
int sumchar=0;
clock_t start,end;
start=clock();
while(infile.get(c)){
m1[c]++;
sumchar++;
}
std::map<char,int>::iterator it1=m1.begin();
for(;it1 != m1.end(); it1++){
m2.insert(pair<double,char>((it1->second*1.0/sumchar),it1->first));
}
end=clock();
cout<<"共计:"<<(end-start)/1000<<"毫秒"<<endl;
//cout<<(end-start)/CLOCKS_PER_SEC<<"秒"<<endl;
cout<<"总计:"<<sumchar<<"个字符"<<endl<<endl;
std::multimap<double,char>::iterator it2=m2.begin();
for(;it2 != m2.end();it2++){
cout<<it2->second<<" "
<<setw(4)<<it2->first*100<<"%"
<<endl;
}
}欢迎与我分享你的看法。 转载请注明出处:http://taowusheng.cn/