2014-12-06 93 views
0

我的意思是寫一些程序,它將從文本文件中讀取文本並擦除給定的單詞。String.erase給出out_of_range異常

不幸的是,什麼是錯用這個代碼特定部分,我得到下面的異常通知:

本文是基於所謂的其他textterminate扔 的「性病實例後只是一個樣本,:: out_of_range 「什麼<>:Basic_string_erase

我想這有什麼錯我用擦,我試圖用做而循環,確定其目的是要被刪除的每一個字的開頭方式循環完成並最終完成擦除文本的開始處,這意味着要被擦除,並結束它 - 我使用它的長度。

#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; 

} 
+0

你可能不希望()'在調用'find'添加'str2.size到'positionOfPhrase'。嘗試輸入:「文本文本文本文本」。 – wimh 2014-12-06 10:21:22

+0

@Wimmel它的工作! :)非常感謝,M8。最後,它適用於每種類型的輸入。 – 2014-12-06 10:36:33

回答

0

我覺得你的問題是,positionOfPhrase內做循環可以是字符串::非營利組織,在這種情況下,擦除會拋出異常。這可以通過更改邏輯來修復:

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

它的工作,但令人驚訝的是,當我輸入文本:「文本文本文本文本」,只有兩個單詞被刪除,我得到了「text__text」的輸出,這很奇怪:( – 2014-12-06 10:27:06

1

您的功能錯誤。你完全不清楚爲什麼你要兩次找到方法。

請嘗試下面的代碼。

#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