无法从文件中读取文本

Trouble reading text from file

我有一个包含以下行的文本源文件

Hello, "#%First sentence with #"

我需要将所有 #% 替换为 1% 参数是文件名,#% as from,1% as to

这是我的代码,

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();
}

在这段代码中,在第一个 while 循环中,当代码读取 std::getline(source, line) 该行被接收为

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

在内部 while 循环中,代码无法找到 #%,即使它存在。

如果行中没有引号,此代码运行良好。

请提出修改建议。

我已修改代码以在扫描每一行之前重置 pos。逻辑完美。

while (std::getline(source, line)) {
    lineNumber++;
    pos = 0;

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