我试图找到一种方法来用新行替换文件中包含字符串的行。
如果文件中不存在该字符串,则将其附加到文件中。
有人可以提供示例代码吗?
编辑:无论如何,如果我需要替换的行位于文件末尾?
尽管我认识到这不是最明智的方法,但以下代码逐行读取demo.txt并搜索单词cactus以将其替换为Oranges,同时将输出写入名为result.txt的辅助文件。
别担心,我为你节省了一些工作。阅读评论:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string search_string = "cactus";
string replace_string = "oranges";
string inbuf;
fstream input_file("demo.txt", ios::in);
ofstream output_file("result.txt");
while (!input_file.eof())
{
getline(input_file, inbuf);
int spot = inbuf.find(search_string);
if(spot >= 0)
{
string tmpstring = inbuf.substr(0,spot);
tmpstring += replace_string;
tmpstring += inbuf.substr(spot+search_string.length(), inbuf.length());
inbuf = tmpstring;
}
output_file << inbuf << endl;
}
//TODO: delete demo.txt and rename result.txt to demo.txt
// to achieve the REPLACE effect.
}
Run Code Online (Sandbox Code Playgroud)