我写了一个程序来查找和替换文件中的一行。该计划是这样的:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(){
fstream f,g; string s,s2,s3;
f.open("sasuke.txt",ios::in);
g.open("konoha.txt",ios::out);
cout<<"Enter line to be replaced: "<<endl;
getline(cin,s2);
cout<<"To be replaced with? "<<endl;
getline(cin,s3);
while(getline(f,s)){
s.replace(s.find(s2),s2.size(),s3);
g<<s<<endl;
}
g.close();
f.close();
return 0;
}
我给出的错误是
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::replace: __pos (which is 18446744073709551615) > this->size() (which is 105)
Aborted (core dumped)
任何人都可以解释一下为什么会出现这个错误以及如何解决它?
答案 0 :(得分:1)
这就是发生的事情。让我们说你要替换的行是&#34; src&#34;,它将替换为&#34; dst&#34;。现在,您的程序逐行浏览输入文本文件,并在找到&#34; src&#34;时替换它。与&#34; dst&#34;。但是,在某些时候,它遇到的行不包含任何文本&#34; src&#34;。然后,find返回一些无效的数字,程序终止抱怨你给替换的位置无效。
所以,让我们说你的sasuke.txt如下:
this is src
this line has src
this line too has src
but not this line
现在,您的代码将一直运行到它将终止的最后一行。为了证明这一点,我在while循环中添加了一个小cout。见输出:
Enter line to be replaced:
src
To be replaced with?
dst
in the while loop
this is src
in the while loop
this line has src
in the while loop
this line too has src
in the while loop
but not this line
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::replace: __pos (which is 18446744073709551615) > this->size() (which is 17)
解决方案是你需要先执行find()操作,查看返回的位置是否有效,然后才能执行exectue replace。对我来说这很有效:
while(getline(f,s)){
size_t pos = s.find(s2);
if(pos < s.length())
s.replace(pos,s2.size(),s3);
g<<s<<endl;
}