I’ve got problem with erase function from string. I can’t remove a single character from certain index.
Maybe I can’t use int “i” as iterator ? I want to remove some characters.
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
void deleteChars(string inputText, string inputChars);
int main(int argc, char *argv[])
{
string tekst1 = ("mama fama lilo babo sabo");
string tekst2 = ("mabo");
deleteChars(tekst1, tekst2);
system("PAUSE");
return EXIT_SUCCESS;
}
void deleteChars(string inputText, string inputChars){
int a = inputText.size();
int b = inputChars.size();
string tmp = inputText;
for(int i=0; i<a; i++){
for(int j=0; j<b; j++){
if(inputText.at(i)==inputChars.at(j)){
tmp.erase(i,1); //Here is my problem ?
}
}
}
inputText = tmp;
cout<<"text: "<<inputText<<endl;
}
My error:
This application has requested the Runtime to terminate it in an unusual way
In the beginning, the size of
tmpis equal to the size ofinputTextwhich isa.But as soon as you erase a character from
tmp, its size decreases by one, and becomesa-1, and if you erase second time, its size would becomea-2and so on. So it is possible that at some point, you will pass an index greater than or equal to the size oftmp, to theerasefunction, which results instd::out_of_rangeexception which you don’t handle and so your application crashes.