You are almost there but the order of your program is slightly wrong. Also you need to open up a file to write to.Code:#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
string r_place;
string word;
ifstream f_in("example.txt");//open file to READ
cout<<"Enter word you wish to replace"<<endl;
cin>>word;
cin.ignore();
int size = word.length();//find the length of the word
cout<<"Enter word you wish to replace it with"<<endl;
getline(cin,r_place,'\n');
cin.ignore();
cout<<"\n\n";
string search;
ofstream f_out("update.txt");//open file to WRITE
while(getline(f_in, search, '\n'))//read in a line
{
string::size_type pos = -1;
while( ( pos = search.find(word, pos+1) ) != string::npos )
{
search.replace(pos,size,r_place);
//search.erase( (search.begin() + pos), (search.begin() + (pos + size)) );
//search.insert( pos, r_place );
}
f_out << search << endl;//Write to file
}
f_in.close(); //close file (reading)
f_out.close(); //close file (writing)
cin.get();
}
The corrected file is named "update.txt"
Sample input:Code:example.txt
---------------
Hello
my
name
is
treenef
Code:Enter word you wish to replace
treenef
Enter word you wish to replace it with
Sam Granger
Code:update.txt
-------------
Hello
my
name
is
Sam Granger