我担心你可能不得不重写整个文件.您可以这样做:
#include
#include
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.