用ifstream实现文件内容的搜索

   2024-09-30 9440
核心提示:ifstream 是 C++ 中的一个类,用于从文件中读取数据#includeiostream#include fstream#includestringint main() {std::ifstream

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)。如果找到关键字,程序将输出包含该关键字的行及其行号。如果在文件中没有找到关键字,程序将输出相应的消息。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号