【问题标题】:String.erase giving out_of_range exceptionString.erase 给出 out_of_range 异常
【发布时间】:2014-12-06 10:07:05
【问题描述】:

我本来打算写一些程序来从文本文件中读取文本并删除给定的单词。

不幸的是,这部分代码有问题,我收到以下异常通知:

此文本只是一个示例,基于抛出后调用的其他文本终止 'std::out_of_range' 的一个实例 what: Basic_string_erase

我猜我使用擦除的方式有问题,我正在尝试使用 do while 循环,确定每次循环时要擦除的单词的开头完成并最终擦除从要擦除的单词开头和结尾开始的文本-我正在使用它的长度。

#include <iostream> 
#include <string> 

using namespace std; 

void eraseString(string &str1, string &str2) // str1 - text, str2 - phrase 
{
   size_t positionOfPhrase = str1.find(str2); 

   if(positionOfPhrase == string::npos)
   {
      cout <<"Phrase hasn't been found... at all"<< endl; 
   }
   else
   {
     do{
        positionOfPhrase = str1.find(str2, positionOfPhrase + str2.size()); 
        str1.erase(positionOfPhrase, str2.size());//**IT's PROBABLY THE SOURCE OF PROBLEM**
     }while(positionOfPhrase != string::npos); 
    }
}

int main(void) 
{
   string str("This text is just a sample text, based on other text"); 
   string str0("text"); 

    cout << str; 
    eraseString(str, str0); 
    cout << str; 

}

【问题讨论】:

  • 您可能不想在对find 的调用中将str2.size() 添加到positionOfPhrase。尝试输入:text text text text
  • @Wimmel 成功了! :) 非常感谢,m8。最后,它适用于所有类型的输入。

标签: c++ string erase


【解决方案1】:

你的功能是错误的。完全不清楚为什么你调用方法 find 两次。

试试下面的代码。

#include <iostream>
#include <string>

std::string & eraseString( std::string &s1, const std::string &s2 )
{
    std::string::size_type pos = 0;

    while ( ( pos = s1.find( s2, pos  ) ) != std::string::npos )
    {
        s1.erase( pos, s2.size() );
    }

    return s1;
}

int main()
{
    std::string s1( "This text is just a sample text, based on other text" ); 
    std::string s2( "text" ); 

    std::cout << s1 << std::endl;
    std::cout << eraseString( s1, s2 ) << std::endl;

    return 0;
}

程序输出是

This text is just a sample text, based on other text
This  is just a sample , based on other 

【讨论】:

    【解决方案2】:

    我认为你的问题是 do 循环中的 positionOfPhrase 可以是 string::npos,在这种情况下擦除会抛出异常。这可以通过将逻辑更改为:

    while (true) {
        positionOfPhrase = str1.find(str2, positionOfPhrase + str2.size());
        if (positionOfPhrase == string::npos) break;
        str1.erase(positionOfPhrase, str2.size());
    }
    

    【讨论】:

    • 它起作用了,但令人惊讶的是,当我输入文本时:“text text text text”,只删除了两个单词,我得到“text__text”的输出,这很奇怪:(
    猜你喜欢
    • 1970-01-01
    • 2017-11-26
    • 2015-10-09
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多