c++ 高手请进 文本替换

来源:百度知道 编辑:UC知道 时间:2024/06/04 23:39:15
#include<iostream.h>
#include<fstream.h>

using namespace std;

int main()
{
ifstream ifs("temp.txt");
ofstream ofs("run.txt");
string str;
string match="finds";
string replace="find";
while(ifs)
{
getline(ifs, str);
string::size_type pos=0;
while(pos!=-1)
{
pos= str.find(match);
if(pos == -1) break;
str.replace(pos, pos+match.length(), replace.c_str());
cout<<pos<<","<<pos+match.length()<<endl;
}
if(ifs)
{
ofs.write(str.c_str(), str.length());
ofs&

1.可能你没有注意到replace的用法,第二项是说替换多长,而不是替换到什么位置,参照下面代码里写的就可以了。
2.头文件里面缺少了<string>, 这在我的编译器上编不过,应该是漏写了吧。
3.我精简了一下你的代码:)你斟酌的使用一下:)
#include<iostream>
#include<fstream>
#include<string>

using namespace std;

int main()
{

ifstream ifs("temp.txt");
ofstream ofs("run.txt");
string str;
string match="finds";
string replace="find";
while(ifs.peek() != EOF)
{
getline(ifs, str);
int pos ;
while((pos = str.find(match)) != str.npos)
{
str.replace(pos, match.length(), replace);
cout<<pos<<","<<pos+match.length()<<endl;
}
ofs<<str<<endl;
}
ifs.close();
ofs.close();
//delete "input.txt"
//rename "temp.txt", "input.txt"
}