Reputation: 138
So I have a program to simulate how a macro works in a compliler. The input program is take in a file : Say input.txt (Text file).
Supposed it had contents like this :
#include<iostream>
#define PI 3.14
What I want to do is, find the occurrence of the word PI after this and replace it with 3.14 in the file. I use FilePointer>>CharacterBuffer to read word by word from the file. How do I replace it in the file after doing all this?
Thanks.
Upvotes: 0
Views: 2385
Reputation: 10733
You can try with following code for replacing a string in a file:-
string line;
size_t len = stringToReplace.length(); //replace is a string to be replaced.
while (getline(in, line))
{
while (true)
{
size_t pos = line.find(stringToReplace);
if (pos != string::npos)
line.replace(pos, len, stringToReplace);
else
break;
}
out << line << '\n';
}
Upvotes: 1