![]() |
#2
yyblackyy2010-04-05 16:04
#include<iostream>
#include<fstream> #include<cctype> #include<iomanip> #include<cstdlib> #define Maxpath 80 //文件名最大长度 using namespace std; //functions int fre[26]; //记录次数的 const char str[]="abcdefghijklmnopqrstuvwxyz"; // 字母表 static int up=0,low=0,wsp=0,total=0; // up 为 大写的个数 low为小写的,wsp为空,制表符。。。total 总数 void frequency(char ch); //记录大小写的函数 void count(char filename[]); //记录总的函数 void print(); //打印的函数 int main() { char filename[Maxpath]; //文件名 cout<<"输入文件全名:"<<endl; cin.getline (filename,Maxpath); //获得文件名 count(filename); //记录个数 print(); //打印 return 0; } //************************************************ void frequency(char ch) { for(int i=0;i<26;i++) if(ch==str[i]) //判断是哪个字母,那个字母代表的个数加一 { fre[i]++; break; //跳出本次循环 } } //************************************************************ void count(char filename[]) { fstream istr; char ch,ch2; istr.open (filename,ios::in); //打开文件 打不开退出 if(istr.fail ()) { cout<<"Can't open!"<<endl; exit(1); } do //记录个数 { ch=istr.get (); if(isspace(ch)) //判断是否是 space wsp++; else if(isalpha(ch)) //判断是否是 字母 { if(isupper(ch)) //是否是大写 up++; else //是否是小写 low++; ch2=tolower(ch); //转成小写 配合str[] 字符串 frequency(ch2); //记录abc的单独的个数 } else ; total++; //总数+1 }while(!istr.eof()); total-=1; //最后的总数 } //***************************************************************** void print() { int Count=0; //cout<<"输入要显示的最小个数的字母"<<endl; //这里可以添加一点小的功能 //cin>>Count; cout<<"Letter Frequencies:"<<endl; for(int i=0;i<26;i++) { if(fre[i]>Count) //判断个数 只显示个数大于Count的字母 cout<<char(toupper(str[i]))<<setw(6)<<fre[i]<<endl; //格式输出如: } //大写的字母 // 对应的次数 A 3 cout<<endl; // B 4 cout<<"Rest of Letters"<<endl; // C 5 cout<<"Upper Case"<<endl; //up cout<<up<<endl; cout<<"Lower Case"<<endl; //low cout<<low<<endl; cout<<"White Space"<<endl; // space cout<<wsp<<endl; cout<<"Total char"<<endl; cout<<total<<endl; //总数 } ![]() |
获取一个文件,必须要function call
计算文件里面字母的 “频率”A~Z(大小写不分)然后再计算里面 write space 的概率
再计算 大小写的概率
结果如下(举例)
Letter Frequencies:
A 10
B 13
C 20
D 0
E 17
F 4
Rest of Letters
Upper Case
50
Lower Case
17
White Space
10