下面编写程序统计一个文件中的字符总数、非空白字符总数、字母总数和平均单词长度,并输出到屏幕和输出文件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();//关闭文件
}
这个后面的数字是统计每行有多少个字符,包括空格和换行符:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3b4cf582b0da085671cc424c427d8ab2.png)
这个是output.txt文件内的内容,这个是相对路径创建的:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/aee5de07f4c32653d7615023ce7714c6.png)