溫馨提示×

用ifstream實現文件內容的搜索

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

ifstream 是 C++ 中的一個類,用于從文件中讀取數據

#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 的文件。然后,它逐行讀取文件內容,并在每一行中搜索指定的關鍵字(在這個例子中是 search_keyword)。如果找到關鍵字,程序將輸出包含該關鍵字的行及其行號。如果在文件中沒有找到關鍵字,程序將輸出相應的消息。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女