[英]String.erase giving out_of_range exception
我本打算編寫一些程序,該程序將從文本文件中讀取文本並擦除給定的單詞。
不幸的是,這部分代碼有問題,我收到以下異常通知:
這段文字只是一個示例,它基於拋出'std :: out_of_range'what <>實例之后調用的其他textterminate: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;
}
您的功能有誤。 完全不清楚為什么要互相調用兩次方法查找。
請嘗試以下代碼。
#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
我認為您的麻煩是do循環內的positionOfPhrase可以是string :: npos,在這種情況下,擦除將引發異常。 可以通過將邏輯更改為:
while (true) {
positionOfPhrase = str1.find(str2, positionOfPhrase + str2.size());
if (positionOfPhrase == string::npos) break;
str1.erase(positionOfPhrase, str2.size());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.