Click here to Skip to main content
14,360,161 members
Rate this:
Please Sign up or sign in to vote.
See more:
I am trying to find a word an replace it in the text file. Now, i can find the word successfully in the text file but i am unable to replace it. Can anyone please suggest me where i made the mistake. Thanks.


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

using namespace std;

int main(){
ifstream input;
ofstream output;
output.open("Book1.txt",ios::app);

int choice;
size_t pos;
size_t p;
string line;
string a;
string id;
cout<<"enter the name you want to search"<<endl;
cin>>a;

string replace = "hello";
size_t len = a.length();
input.open("Book1.txt",ios::out);
if(input.is_open())
{
while(getline(input,line))
{
pos = line.find(a);
if(pos!=string::npos)
{

line.replace(pos,len,replace);

cout<<"Name://IDnumber//Account-Balance"<<" "<<line<<endl;


}
}
}

system("pause");

}
Posted
Updated 6-Nov-19 3:33am
Comments
Richard MacCutchan 20-Nov-14 7:43am
   
You should have an output file, and every time you read a line, you also write it to the output file, whether it is changed or not.

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

read the whole file in a string and use replace.

Check that all strings are replaced and than write the new string to the file
   
Comments
Surajit Das 20-Nov-14 5:23am
   
@KarstenK- I am sorry but i couldnt understand. Can you give me an example?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100