输入输出流

下面编写程序统计一个文件中的字符总数、非空白字符总数、字母总数和平均单词长度,并输出到屏幕和输出文件output.txt。这个要用到输入输出流
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
bool isalph(char c)
{
	return ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'));
}
void main()
{		
	ifstream inf("main.cpp");
	char buf[80];
	inf.getline(buf, 80);
	int count = 0;
	cout << buf << " ----- " << inf.gcount() << endl;
	count += inf.gcount();
	while (!inf.eof())
	{
		inf.getline(buf, 80);		
		cout << buf << " ----- " << inf.gcount() << endl;
		count += inf.gcount();
	}
	cout << "文件中的字符总数:" << count << endl;
//这个是把空格的字符去掉:
	ifstream inf1("main.cpp");
	char c;
	int num = 0;
	ifstream infile;
	infile.open("main.cpp", ios::in);
	while (!inf1.eof())
	{
		inf1.get(c);
		inf1 >> ws;//提取前置空格
		num++;
}
	cout <<"非空白字符总数:"<< num << endl;
//这个是单词总个数:
	ifstream inf2("main.cpp");
	char text[80];
	bool inworld = false;
	int words = 0;
	int i;
	while (!inf2.eof())
	{
		inf2.getline(text, 999);
		i = 0;
		while (text[i]!=0)
		{
			if (!isalph(text[i]))
			{
				inworld = false;
			}
			else if(isalph(text[i])&&inworld==false)
			{
				words++;
				inworld = true;
			}
			i++;
		}
	}
	cout << "单词总个数:" << words << endl;
//这个是字母的总数:
	ifstream inf3("main.cpp");
	char c1;
	int total=0;
	while (inf3.get(c1))
	{
		if ((c1 >= 'A' && c1 <= 'Z') || (c1 >= 'a' && c1 <= 'z'))
		{
			total++;
		}		
	}
	cout <<"字母总数为:"<< total << endl;
/*********************************************************/
	cout << "单词平均长度为:" << total / words << endl;
/*********************************************************/
//创建个output.txt的文件,并且把下面的内容写进这个文件内。
	ofstream outfile;
	outfile.open("output.txt", ios::out);
	outfile<< "文件中的字符总数:" << count << endl;
	outfile << "非空白字符总数:" << num << endl;
	outfile<< "单词平均长度为:" << total / words << endl;
	outfile.close();//关闭文件
}
这个后面的数字是统计每行有多少个字符,包括空格和换行符:

在这里插入图片描述

这个是output.txt文件内的内容,这个是相对路径创建的:

在这里插入图片描述

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值