I want to edit a text file using c++. Suppose the content of the file is: I am a boy. I am 20 years old. I live in India. Now I want to make it: I am a boy. I am 22 years old. I live in India. I want to change it this way. Find a particular word and replace it. Is it possible to do it this way rather than replacing the whole file by duplicating the the unchanged content. Please help me.
I found this code ages ago, and it's worked nicely for me. #include <iostream> #include <string> #include <sstream> using namespace std; int main() { string originalText = "This is a test string"; string search = "test"; string replace = "new"; string buffer = ""; stringstream replaced(""); stringstream original(originalText); while (original >> buffer) { if (buffer == search) replaced << replace << " "; else replaced << buffer << " "; } cout << replaced.str(); return 0; } Code (markup):
You do know how to read and write a text file right? By using above algorithm, it can be done. 1- Read the text file 2- Find the word (by using string) that you want to change 3- Replace the string Done