gpt4 book ai didi

c++ - 替换文本文件中的一行

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:10:05 25 4
gpt4 key购买 nike

我想替换文件中的一行文本,但我不知道执行此操作的函数。

我有这个:

ofstream outfile("text.txt");
ifstream infile("text.txt");

infile >> replace with other text;

有什么答案吗?

我想说的是,为了在文件的某行中添加文本...

示例

infile.add(text, line); 

C++ 有这方面的功能吗?

最佳答案

恐怕您可能不得不重写整个文件。以下是您可以如何做到的:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
string strReplace = "HELLO";
string strNew = "GOODBYE";
ifstream filein("filein.txt"); //File to read from
ofstream fileout("fileout.txt"); //Temporary file
if(!filein || !fileout)
{
cout << "Error opening files!" << endl;
return 1;
}

string strTemp;
//bool found = false;
while(filein >> strTemp)
{
if(strTemp == strReplace){
strTemp = strNew;
//found = true;
}
strTemp += "\n";
fileout << strTemp;
//if(found) break;
}
return 0;
}

输入文件:

ONE
TWO
THREE
HELLO
SEVEN

输出文件:

ONE
TWO
THREE
GOODBYE
SEVEN

如果您只希望它替换第一次出现,只需取消注释行。另外,我忘了,最后添加删除filein.txt并将fileout.txt重命名为filein.txt的代码。

关于c++ - 替换文本文件中的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9505085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com