The number of characters to obtain a document which, the number of letters, numbers, number, number of words, the number of non-whitespace characters, the average total number of words.
Code is as follows:
Calculate.h Code:
#include <iostream>
using namespace std;
void calculate();
Main.cpp Code:
#include "calculate.h"
//这是测试数字123
void main() {
calculate();
}
Calculate.cpp Code:
#include "calculate.h"
#include <fstream>
void calculate() {
bool ing = false;
char a;
int x = 0; //字符总数
int y = 0;//数字总数
int z = 0;//字母总数
int k = 0;//单词数量
ifstream list("main.cpp");//读取main.cpp的内容
while (list.get(a))//输出main.cpp的内容
{
x++;
if (a>='a'&& a <= 'z'|| a >= 'A' && a <= 'Z')//判断是否为字母
{
z++;
ing = true;//判断为字母的时候bool为真
}
else if (a == ' ' || a == '\n' || a == '\t' || a =='.')//判断是否是空格
{
if (ing == true) {//判断为bool是否为真,为真就进行自增
k++;
ing = false;//自增后将bool改为假
}
}
else if (a >= '0'&&a<='9') {//判断是否是数字
y++;
if (ing == true) {//判断为bool是否为真,为真就进行自增
k++;
ing = false;//自增后将bool改为假
}
}
}
if (ing == true) {//判断结束以后最后一个是否为字母单词,为真就进行自增
k++;
ing = false;//自增后将bool改为假
}
cout << "字符总数:" << x << "个" << endl;
cout << "字母总数:" << z << "个" << endl;
cout << "数字总数:" << y << "个" << endl;
cout << "单词总数:" << k << "个" << endl;
cout << "非空白字符总数:" << z+y << "个" << endl;
cout << "平均单词总数:" << z/k << "个" << endl;
list.close();//关闭输入
ofstream out("Output.txt");//输出到文本
out << "字符总数:" << x << "个" << endl
<< "字母总数:" << z << "个" << endl
<< "数字总数:" << y << "个" << endl
<< "单词总数:" << k << "个" << endl
<< "非空白字符总数:" << z+y << "个" << endl
<< "平均单词总数:" << z/k << "个" << endl;
out.close();//关闭输出
}
Operating results are as follows:
generate txt file
txt file content