统计文件中的字符和符号数量程序设计

统计文件中的字符和符号数量程序设计

一 初级要求

  1. 需要用到文件操作及相关函数,对磁盘中的文件进行读写,其用法类似于屏幕输入输出。
  2. 统计和输出其中包含空格数量,数字及符号的数量,英文字符数量,英文单词数量(规定单词间以一个或多个空格分开)。
    二 高级要求
  3. 统计段落数。
  4. 能够分别统计出中文字符和英文字符个数。
  5. 统计信息输出到文件结尾。
主函数
int main()
{
	int i = 0;
	char str[MAX_LINE] = "";
	char s[MAX_LINE] = "";
	int chinese,word;
	FILE *read;//文件指针
	FILE *write=fopen("hao.txt", "a");
	char c;
	read = fopen("hao.txt", "r");//以只读方式打开
	c = fgetc(read);
	while (c != EOF||i<strlen(str)) 
	{
		str[i] = c;
		c = fgetc(read);
		i++;
	}
	puts(str); 
	count_1();
	chinese=count_zw(str);//统计单词个数
	word=count_word(str);//统计中文字符个数 
	sprintf(s, "汉    字:%d个\n单    词:%d\n个",chinese,word);
	fputs(s, write);  //写入文件
	fclose(write);
	fclose(read);
	system("pause");
	return 0;
}
初级要求
void count_1()//任务要求一
{
//	int n;
	int l = 0, m = 0, j = 0, p = 0,para = 1;//l:英文字母数;m:空格数;j:数字个数;p:符号个数
	char s[MAX_LINE] = "";
	FILE *w=fopen("hao.txt","r");
	FILE *write=fopen("hao.txt", "a");
	int ch;
	while ((ch=fgetc(w))!=EOF)
	{
		if (ch == ' ')
			m++;
		else if (ch >= '0'&&ch <= '9')
			j++;
		else if ((ch <= 'z'&&ch >= 'a') || (ch >= 'A'&&ch <= 'Z'))
			l++;
		else if((ch>=33&&ch<=47)||(ch>=58&&ch<=64)||(ch>=91&&ch<=96)||(ch>=123&&ch<=126))
			p++;
		else if(ch==10||ch==27||ch==EOF)   //统计文章的段落 
			para++;
	}
	fclose(w);
	sprintf(s, "\n段    落:%d\n英文字母:%d个\n空    格:%d个\n数    字 : %d个\n符    号:%d个\n",para,l,m,j,p);
//	FILE *write=fopen("hao.txt", "a");
	fputs(s, write);
	fclose(write);
	printf("英文字母:%d个\n", l);
	printf("空    格:%d个\n", m);
	printf("数    字:%d个\n", j);
	printf("符    号:%d个\n", p);
	printf("段    落:%d段\n", para);
}
int count_word(char str[])//统计单词个数
{
	int num = 0;
	int i=0;
	for (i = 0; str[i]!= '\0'; i++){
		if((str[i]>='A'&&str[i]<='Z')||(str[i]>='a'&&str[i]<='z'))
		{
			if(str[i+1]==' '||str[i+1]=='.'||str[i+1] =='?'||str[i+1]=='!'||str[i+1]=='\0'||str[i+1]==10)
				num++;
		}
	}
	printf("单词个数:%d个\n",num);
	return num;
}
int count_zw(char str[])//统计中文
{
	int i,h=0;
	for (i = 0; i < strlen(str); i++)
	{
		if((str[i]<='A'||str[i]>='Z')||(str[i]<='a'||str[i]>='b'))
		{
			if (str[i] < 0&&str[i+1]<0)  //汉字对应的ASCLL值为负 
			{
				h++;
				i++;     //汉字占两个字符,所以i要加两次
			}	
		}		
	}
	printf("汉   字%d个\n", h);
	return h;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值