Trouble reading text from file

  Uncategorised

I have a text source file which contains the following line

Hello, "#%First sentence with #"

I will need to replace all #% to 1%
The arguments are filename, #% as from, 1% as to

Here is my code,

void UpdateSourceFile (std::string sourceFile, const std::string from, const std::string to) 
{
    std::string line;
    int lineNumber = 0, pos = 0;
    int flen = from.length();
    int tlen = to.length();

    std::ifstream source(sourceFile.c_str());

    while (std::getline(source, line)) {
        
        lineNumber++;
        
        while ((pos = line.find(from, pos)) != std::string::npos) {
            line.replace(pos, flen, to);
            pos += tlen;
        }
    }
    source.close();
}

In this code, in the first while loop, when the code reads std::getline(source, line)
the line is received as

"Hello, "#%First sentence with #""

In the inner while loop, the code fails to find #% even though it’s present.

This code works well if the quotation aren’t present in the line.

Please suggest modification.

Source: Visual Studio Questions

LEAVE A COMMENT