Reputation: 1
I was meant to write some program which will read text from text file and erase given words.
Unfortunately, something's wrong with this particular part of code, I get the following exception notification:
This text is just a sample, based on other textterminate called after throwing an instance of 'std::out_of_range' what<>: Basic_string_erase
I guess that there is something wrong with the way I use erase, I'm trying to to use do while loop, determine the beginning of word which is meant to be erased every time the loop is done and eventually erase text which begins at the beginning of word which is meant to be erased and the end of it - I'm using its length.
#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;
}
Upvotes: 0
Views: 1746
Reputation: 310940
Your function is wrong. It is entirely unclear why you call method find twice after each other.
Try the following code.
#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;
}
The program output is
This text is just a sample text, based on other text
This is just a sample , based on other
Upvotes: 1
Reputation: 69
I think your trouble is that positionOfPhrase inside do loop can be string::npos, in which case erase will throw an exception. This can be fixed by changing logic to:
while (true) {
positionOfPhrase = str1.find(str2, positionOfPhrase + str2.size());
if (positionOfPhrase == string::npos) break;
str1.erase(positionOfPhrase, str2.size());
}
Upvotes: 0