#include <iostream> #include <cstdio> #include <fstream> #include <algorithm> using namespace std; struct info { char che; int cnt; bool operator < (const info &a) const { return a.cnt > cnt; } }; typedef struct info pt; const int Maxl = 30; void init(pt *freq); //初始化字符统计数组 int read(char &ch); //读入一个字符,并标准化 int main(void) { ifstream cin("aaa.txt"); pt freq[Maxl]; //freq是结构体数组,存储每个字符及其对应的统计个数 char ch; bool flag = true; while(flag) { init(freq); while(read(ch)) { freq[ch - 'a'].cnt++; } sort(freq, freq + 26); //输出字符及统计个数 int i; for(i = 0; i < 26; i++) { cout << freq[i].che << " : " << freq[i].cnt << endl; } //询问用户要不要继续进行字符串统计 cout << "Do you want to continue?/n N or other" << endl; char cha; cin >> cha; if(cha == 'N') { flag = false; } else { flag = false; } } return 0; } void init(pt *freq) { int i; for(i = 0; i < Maxl; i++) { freq[i].che = 'a' + i; freq[i].cnt = 0; } } int read(char &ch) { char chd; while(cin >> chd) { if(chd >= 'A' && chd <= 'Z') { ch = chd + 'a' - 'A'; return 1; } else if(chd >= 'a' && chd <= 'z') { ch = chd; return 1; } else continue; } return EOF; }