在文件C ++中替换行 [英] replace line in a file C++
问题描述
如果字符串不存在,我将尝试在一个文件中找到一个替换包含一个字符串的行的方法。
有人可以提供示例代码吗?
虽然我知道这不是最聪明的方式来执行此操作,以下代码逐行读取 demo.txt ,并搜索单词 cactus 以替换 oranges while将输出写入名为 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:删除demo.txt并将result.txt重命名为demo.txt
//以实现REPLACE效果。
}
I'm trying to find a way to replace a line, containing a string, in a file with a new line.
If the string is not present in the file, then append it to the file.
Can someone give a sample code?
EDIT : is there anyway if the line that i need to replace is at the end of the file?
Although I recognize that this is not the smartest way to do it, the following code reads demo.txt line by line and searches for the word cactus to replace it for oranges while writing the output to a secondary file named result.txt.
Don't worry, I saved some work for you. Read the comment:
#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.
}
这篇关于在文件C ++中替换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!