【问题标题】:Runtime error in replace function?替换功能中的运行时错误?
【发布时间】: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


【解决方案1】:

这就是发生的事情。假设您要替换的行是“src”,它将被替换为“dst”。现在,您的程序逐行遍历输入文本文件,并在找到“src”时将其替换为“dst”。但是,在某个时间点,它会遇到不包含任何文本“src”的行。然后,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()操作,看看返回的位置是否有效,然后再执行replace。对我来说这很有效:

while(getline(f,s)){
    size_t pos = s.find(s2);
    if(pos < s.length())
        s.replace(pos,s2.size(),s3);
    g<<s<<endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-16
    • 2020-06-22
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 2010-10-08
    • 2010-12-01
    • 1970-01-01
    相关资源
    最近更新 更多