c++ - String.erase giving out_of_range exception -
i meant write program read text text file , erase given words.
unfortunately, something's wrong particular part of code, following exception notification:
this text sample, based on other textterminate called after throwing instance of 'std::out_of_range' what<>: basic_string_erase
i guess there wrong way use erase, i'm trying to use do while loop, determine beginning of word meant erased every time loop done , erase text begins @ beginning of word meant erased , end of - i'm using 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... @ all"<< endl; } else { do{ positionofphrase = str1.find(str2, positionofphrase + str2.size()); str1.erase(positionofphrase, str2.size());//**it's source of problem** }while(positionofphrase != string::npos); } } int main(void) { string str("this text sample text, based on other text"); string str0("text"); cout << str; erasestring(str, str0); cout << str; }
your function wrong. entirely unclear why call method find twice after each other.
try 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 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 sample text, based on other text sample , based on other
Comments
Post a Comment