⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 文件字符统计.cpp

📁 这个工程详细实现了文件字符统的计(数组应用)
💻 CPP
字号:
// 文件字符统计.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream.h>

class Statistics
{
private:
	int account[26];			//成员变量,用来统计字符出现次数
	int appear[26];			//成员变量,用来对出现次数的多少进行排序
	void Dispatch(char);			//成员函数,用于分析字符并归类
	void Sort();				//成员函数,用于对统计结果进行排序
	void PrintOut();			//成员函数,用于输出结果
public:
	void ReadFromFile(char*);		//成员函数,用于读取文件的操作
};

void Statistics::ReadFromFile(char *filename)
{
		FILE *f;
		char c;
		for(int i=0;i<26;i++)				//初始化account数组
		{
			account[i]=0;
			appear[i]=i;
		}
		if ((f=fopen(filename,"r"))==NULL)	//例外处理
		{
			cout<<"ERROR:Cannot Open File or File does not Exist!"<<endl;
		}
		while(fscanf(f,"%c",&c)!=EOF)		//从文件中读一个字符,并判断是否为文件结束符
		{
			Dispatch(c);				//分析字符并归类
		}
		Sort();						//对统计结果进行排序
		PrintOut();					//输出字符出现次数
}

void Statistics::Dispatch(char c)
{
	if (c>='A' && c<='Z')
		account[int(c-'A')]++;
	if (c>='a' && c<='z')
		account[int(c-'a')]++;
}

void Statistics::Sort()
{
	for(int i=0;i<25;i++)
		for(int j=i+1;j<26;j++)
			if (account[appear[i]]<account[appear[j]])
			{
				int k=appear[i];appear[i]=appear[j];appear[j]=k;
			}
}

void Statistics::PrintOut()
{
		for(int i=0;i<26;i++)
			cout<<char(int('a')+appear[i])<<" has appeared "<<account[appear[i]]<<" times;"<<endl;
}


void main()
{
	Statistics sta;
	sta.ReadFromFile("Example.txt");
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -