溫馨提示×

用ifstream實現(xiàn)文件內(nèi)容的搜索

小樊
81
2024-09-02 19:13:52
欄目: 編程語言

ifstream 是 C++ 中的一個類,用于從文件中讀取數(shù)據(jù)

#include<iostream>
#include <fstream>
#include<string>

int main() {
    std::ifstream file("example.txt"); // 打開文件 "example.txt"
    std::string search_term = "search_keyword"; // 要搜索的關鍵字
    std::string line;
    int line_number = 0;
    bool found = false;

    if (file.is_open()) {
        while (std::getline(file, line)) { // 逐行讀取文件
            line_number++;
            if (line.find(search_term) != std::string::npos) { // 如果找到關鍵字
                std::cout << "Found '"<< search_term << "' in line "<< line_number << ": "<< line<< std::endl;
                found = true;
            }
        }
        file.close(); // 關閉文件
    } else {
        std::cout << "Unable to open file"<< std::endl;
    }

    if (!found) {
        std::cout << "'"<< search_term << "' not found in the file"<< std::endl;
    }

    return 0;
}

這個程序首先打開名為 example.txt 的文件。然后,它逐行讀取文件內(nèi)容,并在每一行中搜索指定的關鍵字(在這個例子中是 search_keyword)。如果找到關鍵字,程序?qū)⑤敵霭撽P鍵字的行及其行號。如果在文件中沒有找到關鍵字,程序?qū)⑤敵鱿鄳南ⅰ?/p>

0