如何在c++中找到文件中不同组字符的总数

  • 本文关键字:字符 文件 c++ c++
  • 更新时间 :
  • 英文 :


当前文件输入/输出困难。我知道使用cctype来区分不同的组,但我不知道如何得到每个组的总数。任何帮助都会非常感激这是作业。编写一个程序,收集特定字符组在文件中出现的次数。

  1. 允许用户指定处理哪个文件。
  2. 计算以下类型字符出现的频率:
    • 字母字符
    • 数字字符
    • 控制字符
    • 大写字符
    • 小写字符
    • 标点符号
    • 文件中的字符总数
  3. 让程序将收集的结果输出到一个名为"stats.txt"的文件中。
  4. 按上述顺序显示信息(左对齐)
  5. 为每组字符类型添加一列,显示这些字符出现的频率。
  6. 添加一个额外的列,显示这个组占总数的百分比文件中的字符数。显示带有一个小数点的数字。(注意:在显示处理的字符总数的行中不需要百分比。
  7. 请确保所有数字列正确对齐,显示适当的精度,形成一个漂亮的垂直表格。

我的代码如下:

enter code here
#include <iostream>
#include <cctype>
#include <fstream>
#include <iomanip>
#include <string>
//included libraries//
using namespace std;
//function definitions//
int main() {
int count;
int character;
string filename;
int alpha = 0, num = 0, con = 0, UC = 0, LC = 0, pun = 0, total = 0;
cout << "Enter file name and extension to process.n";
cin >> filename;
ofstream fileout;
ifstream filein;
//input file//
filein.open(filename);
if (filein.fail()) {
cerr << "Failed to open the file: " << filename << endl;
}

//open file//
fileout.open("stats.txt");
if (fileout.fail()) {
cout << "Error, unable to open output filen";
system("pause");
exit(1);
}
fileout.setf(ios::fixed);
fileout.setf(ios::showpoint);
fileout.precision(3);

filein.close();
fileout.close();
system("pause");
return 0;
}

我不知道如何获得每个

的总数

为此,我建议为包含以下内容的分类函数创建struct:

  • 名称,如Alphabetic
  • 分类函数指针,如std::isalpha
  • 总计数。

struct可能看起来像这样:

struct classifier {
std::string_view heading;   // e.g. "Alphabetic"
int (*class_func)(int);     // e.g. std::isalpha
std::uintmax_t count = 0;   // start out with zero
};

您可以创建这样的structs数组:

std::array<classifier, 6> classifiers{{
{"Alphabetic", std::isalpha},
{"Numeric", std::isdigit},
{"Control", std::iscntrl},
{"Upper case", std::isupper},
{"Lower case", std::islower},
{"Punctuation", std::ispunct},
}};

现在,对于从文件中读取的每个字符,循环遍历分类器并根据分类函数检查该字符,如果匹配,则将其添加到classifier中的count:

char ch = .. read from file ...;
++total_chars;
for(auto& [_, func, count] : classifiers) {
count += func(static_cast<unsigned char>(ch)) != 0;
}

当整个文件被读取时,每个分类器中应该是每个的总和:

for(auto& [heading, _, count] : classifiers) {
std::cout << heading << " characters " << 't' << count << 'n';
}

最新更新