Anirudh Ramesh
Anirudh Ramesh

Reputation: 138

Replacing a particular word in a text file : C++ , to a pre-defined value

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

Answers (1)

ravi
ravi

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

Related Questions