I crated a program which can search a text for a string and gives you every line which conatins that string back.
Now I want to create another text file with the output. But I cant get it to work. Actually I have no problems with creating the text file becasue its creating it but its always empty. I just dont know how to gte the results from the top of my code into the output text file.

Here is my code:

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

using namespace std;

int main(void) {
    string search;
    int offset;
    string line;

    ifstream MyFile;
    cout << "Type the name you want to search" << endl;
    cin >> search;

    if (MyFile.is_open())
        while (!MyFile.eof())
            getline(MyFile, line);
            if ((offset = line.find(search, 0)) != string::npos) {
                cout << "The word was found " << line << endl;


        string filename;
        stringstream str;
        cout << "Name your new text file";
        cin >> filename;
        filename += "_OP.txt";
        cout << filename;
        ofstream (filename.c_str());

        cout << "Wasnt able to open the file!" << endl;
    return 0;