War*_*ock 7 c++ stream ifstream
我想替换文件中的一行文本,但我不知道它的功能.
我有这个:
ofstream outfile("text.txt");
ifstream infile("text.txt");
infile >> replace whit other text;
Run Code Online (Sandbox Code Playgroud)
对此有何答案?
我想念,在文件的某些行添加文字...
例
infile.add(text, line);
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
输入文件:
ONE
TWO
THREE
HELLO
SEVEN
Run Code Online (Sandbox Code Playgroud)
输出文件:
ONE
TWO
THREE
GOODBYE
SEVEN
Run Code Online (Sandbox Code Playgroud)
如果您只希望它替换第一次出现,请取消注释注释行.另外,我忘了,最后添加删除filein.txt的代码并将fileout.txt重命名为filein.txt.