【发布时间】:2018-09-10 23:12:24
【问题描述】:
我编写了一个程序来查找和替换文件中的一行。程序是这样的:
#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)
谁能解释一下为什么会出现这个错误以及如何解决它?
【问题讨论】:
-
您需要检查是否首先使用
s.find(s2)找到字符串之前 运行replace。 -
找不到行怎么办?
-
当抛出你从未捕获的异常时,会自动调用 terminate()。
-
我会为此添加一个 if 语句,但首先我通过输入文件中的一行来尝试它。它仍然显示此错误
标签: c++ string file-handling