C++ 程序没有找到搜索到的词 - 除了第一行

C++ Program is not finding the searched word - except the first line

任务: 创建程序以读取给定的文本文件并将包含给定子字符串的所有行打印到另一个文本文件中。从文件中读取应该逐行执行。

我的代码:

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

int main(){
    string inputFileName = "inputFile.txt";
    string outputFileName = "outputFile.txt";

    fstream inputfile;
    ofstream outputFile; 

    inputfile.open(inputFileName.c_str());
    outputFile.open(outputFileName.c_str());

    string keyWord;
    cout << "Please, enter a key word: " << endl;
    cin >> keyWord;
    string line;
    while (getline(inputfile, line)) {
        // Processing from the beginning of each line.
        if(line.find(keyWord) != string::npos){
            outputFile << "THE LINE THAT IS CONTAINING YOUR KEY WORD: " << "\n" 
            << line << "\n";
        } else 
        cout << "Error. Input text doesn't have the mentioned word." << endl;
        break;
            
    }
    cout << "An output file has been created!";
}

问题:我可以在第一行找到我要搜索的词。 但不是在下面几行(回车后,\n)!

int found = 0;
while (getline(inputfile, line)) {
    // Processing from the beginning of each line.
    if(line.find(keyWord) != string::npos){
        outputFile << "THE LINE THAT IS CONTAINING YOUR KEY WORD: " << "\n" 
        << line << "\n";
        found = 1;
    }
}
if(found == 0)
{ 
    cout << "Error. Input text doesn't have the mentioned word." << endl;
}
        

我知道这个问题已经得到解答,但如果您需要在一行中处理多个关键字,您可以使用下面的示例代码。

const std::string needle{ "KeyWord" };

if ( std::fstream file{ R"(Path\To\Your\File\Test.txt)", std::ios::in } ) 
{
    for ( std::string line; std::getline( file, line ); ) 
    {
        std::size_t pos{ line.find( needle ) };
        for ( ; pos != std::string::npos; pos = line.find( needle, pos + needle.size( ) ) ) 
        {
            std::cout << line.substr( pos, needle.size( ) ) << '\n';
        }
    }
}