C++逐行读取与筛选TXT文件内容的实现方法

C++中,可以轻松实现逐行读取TXT文件内容,并对指定内容进行筛选和输出。以下是主要实现步骤:

  1. 打开文件:使用ifstream类打开TXT文件。
  2. 逐行读取:利用getline函数逐行读取文件内容,每行内容会自动换行。
  3. 指定内容筛选:在读取每行后,通过find函数或正则表达式筛选出包含指定关键词的行。
  4. 输出指定内容:将符合条件的行输出到控制台。

示例代码:

#include 
#include 
#include 

void readAndFilterFile(const std::string &filename, const std::string ⌖) {
    std::ifstream file(filename);
    std::string line;
    if (file.is_open()) {
        while (getline(file, line)) {
            if (line.find(target) != std::string::npos) {
                std::cout << line>

在上面的代码中,readAndFilterFile函数打开指定文件并逐行读取,找到包含指定内容的行后输出。此方法适合处理内容较多、需逐行检查的文件。

rar 文件大小:2.29MB