如题,实现对一个文本文件的读取,将其所有文本中的字母数进行统计(包括大小写),忽略特殊的字符及空格,并将统计的结果以 下列方式输入到另一个文本文件
代码段如下
#include <fstream>
#include <iomanip>
#include <string>
#include <iostream>
#include <numeric>
using namespace std;int main() {
ifstream ifile;
ofstream ofile;
int counts[26] = { 0 };
char str[100];
ifile.open("D://Users//wengy//Desktop//cgaga//in.txt");
ofile.open("D://Users//wengy//Desktop//cgaga//out.txt");//统计输入的文本字母个数
while (ifile.getline(str, 99)) {
for (auto letter : str) {
if (int(letter) >= 65 && int(letter) <= 91) {
counts[int(letter) - 65] ++;
}
//大写
else if (int(letter) >= 97 && int(letter) <= 123) {
counts[int(letter) - 97] ++;
}
else {
continue;
}
}
}
float sum = accumulate(counts, counts + size(counts), 0);
//输出26个字母数统计效果到文本上
for (int i = 0; i < 26; ++i) {
ofile << setprecision(2) << char(i + 65) << " : " << counts[i]*100.0 / sum << "% ";int j = counts[i];
while (j > 0) {
ofile << '|';
j--;
}
ofile << endl;
}
ifile.close();
ofile.close();}
in、out 的理解可以以我们和计算机的交流理解,in指的是它们进入我们,我们获得信息,out指的是我们向他们发出信息,也就是它们接收或者被写入信息,参考对象都是我们自身
#include <fstream>
#include <iomanip>
#include <string>
#include <iostream>
#include <numeric>
using namespace std;
引入头文件,其中 从上往下依次是1.文件流的输入和读取 2.格式化输出 3.string的运用 4.输入输出流 5.accumulate求和的引用 6.命名空间
ifstream ifile;
ofstream ofile;
int counts[26] = { 0 };
char str[100];
ifile.open("D://Users//wengy//Desktop//cgaga//in.txt");
ofile.open("D://Users//wengy//Desktop//cgaga//out.txt");
定义文件类别、打开文件,记得最后一定要关闭文件,定义了一个用来统计26个字母的数组以及一个为了接收文本行的数组
while (ifile.getline(str, 99)) {
for (auto letter : str) {
if (int(letter) >= 65 && int(letter) <= 91) {
counts[int(letter) - 65] ++;
}
//大写
else if (int(letter) >= 97 && int(letter) <= 123) {
counts[int(letter) - 97] ++;
}
else {
continue;
}
}
}
ifile.getline(char,int)中是输入流调用成员函数getline,注意两个参数第一个必须是是一个char数组,用来接收读取的每一行文本,第二个参数是读取的最大字符数,尽量设置大一些
统计大小写是利用ascii码中对的的数值
for (int i = 0; i < 26; ++i) {
ofile << setprecision(2) << char(i + 65) << " : " << counts[i]*100.0 / sum << "% ";int j = counts[i];
while (j > 0) {
ofile << '|';
j--;
}
ofile << endl;
}
char(i+65)可将ASCII码转化为字符, 百分小数通过num*100.0在加上“%”的形式呈现
以上即可实现目标