-3

I don't want to change the text inside the file, just the output. The text in the file reads "C++ is difficult and programming is difficult" What I want the program to do is to read that, but replace the word "difficult" with the word "easy", so that it reads as "C++ is easy and programming is easy" actually touching or replacing anything in the text file.

This is what I have so far:

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

int main() {
    string line;
    ifstream myfile("difficult.txt");
    if (myfile.is_open())
    {
        while (getline(myfile, line))
        {
            cout << line << '\n';
        }
        myfile.close();
    }

    else cout << "Unable to open file";

    return 0;
}
  • 4
    Possible duplicate of [c++ how to replace a string in an array for another string](https://stackoverflow.com/questions/46099606/c-how-to-replace-a-string-in-an-array-for-another-string) – Jean-François Fabre Feb 21 '19 at 20:12

1 Answers1

0

This would be as simple as:

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

using namespace std;

int main(){
    string line;
    ifstream myfile("difficult.txt");

    if (myfile.is_open())
    {
        while (getline(myfile, line))
        {
            if(line == "difficult") cout << "easy" << '\n';
            else cout << line << '\n';

            // OR

            if(line == "difficult") line = "easy";
            cout << line << '\n';
        }

        myfile.close();
    }

    else cout << "Unable to open file";

    return 0;
}
Rokas Višinskas
  • 533
  • 4
  • 12
  • that didn't seem to work. maybe i'm doing something wrong? i ran it in visual studio 2017 and it just outputs the original text without "easy" in it – Frosted Butts Feb 21 '19 at 22:37