使用 C++ 统计文件中字符的出现次数

C++C++Beginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,我们将学习如何使用 C++ 编程来计算文件中某个字符的出现次数。我们将创建一个 C++ 程序,该程序读取文件并计算文件中特定字符出现的次数。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"]) cpp(("`C++`")) -.-> cpp/SyntaxandStyleGroup(["`Syntax and Style`"]) cpp/BasicsGroup -.-> cpp/variables("`Variables`") cpp/BasicsGroup -.-> cpp/data_types("`Data Types`") cpp/BasicsGroup -.-> cpp/strings("`Strings`") cpp/ControlFlowGroup -.-> cpp/conditions("`Conditions`") cpp/ControlFlowGroup -.-> cpp/while_loop("`While Loop`") cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`") cpp/IOandFileHandlingGroup -.-> cpp/files("`Files`") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("`Code Formatting`") subgraph Lab Skills cpp/variables -.-> lab-96159{{"`使用 C++ 统计文件中字符的出现次数`"}} cpp/data_types -.-> lab-96159{{"`使用 C++ 统计文件中字符的出现次数`"}} cpp/strings -.-> lab-96159{{"`使用 C++ 统计文件中字符的出现次数`"}} cpp/conditions -.-> lab-96159{{"`使用 C++ 统计文件中字符的出现次数`"}} cpp/while_loop -.-> lab-96159{{"`使用 C++ 统计文件中字符的出现次数`"}} cpp/output -.-> lab-96159{{"`使用 C++ 统计文件中字符的出现次数`"}} cpp/files -.-> lab-96159{{"`使用 C++ 统计文件中字符的出现次数`"}} cpp/code_formatting -.-> lab-96159{{"`使用 C++ 统计文件中字符的出现次数`"}} end

创建文件

首先,我们需要创建一个包含一些文本的文件。让我们在 ~/project 目录下创建一个名为 example.txt 的文件,并在其中写入一些文本。为此,请在终端中执行以下命令:

echo -e "This is an example file\nIt contains some text" > ~/project/example.txt

包含头文件

在这一步中,包含所需的头文件 iostreamfstreamiostream 用于输入输出操作,而 fstream 用于文件处理操作。在 ~/project 目录下创建一个名为 main.cpp 的新文件,并在文本编辑器中打开它。

#include <iostream>
#include <fstream>
using namespace std;

定义变量

在这一步中,我们定义变量 filename 用于表示输入文件,ch 用于存储程序当前读取的字符,以及 count 用于统计字符在文件中出现的次数。

string filename = "example.txt";
char ch;
int count = 0;

打开并读取输入文件

在这一步中,我们创建一个 ifstream 对象以只读模式打开输入文件 example.txt。然后,我们使用 while 循环逐字符读取文件内容。我们使用 get() 函数从文件中一次读取一个字符。如果读取的字符与我们要统计的字符匹配,则递增 count 变量。

ifstream fin(filename,ios::in);

while(fin.get(ch)){
    if(ch == 'e')
        count++;
}

显示结果

在这一步中,我们显示字符在文件中出现的次数。同时,我们关闭输入文件。

cout << "The number of times 'e' appears in file is: " << count;
fin.close();

编译并运行程序

在这一步中,我们编译 C++ 程序并执行它以统计文件中字符的出现次数。打开终端并导航到 ~/project 目录,然后执行以下命令:

g++ main.cpp -o main && ./main

这将编译并运行 main.cpp 文件。输出将显示字符在文件中出现的次数。

main.cpp 文件的最终代码如下:

#include <iostream>
#include <fstream>
using namespace std;

int main(){
    string filename = "example.txt";
    char ch;
    int count = 0;

    ifstream fin(filename,ios::in);

    while(fin.get(ch)){
        if(ch == 'e')
            count++;
    }

    cout << "The number of times 'e' appears in file is: " << count;
    fin.close();

    return 0;
}

总结

在本实验中,我们学习了如何使用 C++ 编程统计文件中特定字符的出现次数。我们使用 ifstream 对象逐字符读取文件,并统计所需字符的出现次数。同时,我们还在控制台上显示了结果。

您可能感兴趣的其他 C++ 教程