out range error

Hi guys, this is is my function that deciphers lines of code. The first step to decipher is to get rid of all the same chars like aaabbbyyyy ----> aby . The second step is to get rid of all the occurences of the substring of the first three characters of the string, an example would be l.pxyzl.ptol ---> xyztol

For some reason whenever i try to run the program and cout decrypt in the main this error comes up:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::erase
Aborted
I'm not sure how should I fix it. I know it is something wrong with what I erased with the erasing function but not sure how to fix it. I am a beginner in programming so please help me step by step :) .

So far this is my function:

string decrypt (string encrypted)
{

string decrypt,deleted;
int i, pos, n;



for (i=0; i < encrypted.length(); i++)
{
if((pos=decrypt.find(encrypted[i]))<0)
{
decrypt = decrypt + encrypted[i];
}

}

deleted = decrypt.substr(0,3);

decrypt.erase(0,3);

n=decrypt.find(deleted);

decrypt.erase(n,3);

while(decrypt.find(deleted) != decrypt.npos){

n=decrypt.find(deleted);
decrypt.erase(n,3);

}
return decrypt;
}



Last edited on
Have you tried stepping thru the code in a debugger, or tracing the function?
I did and it seems like the error is coming from here, but not sure why.

string decrypt (string encrypted)
{

string decrypt,deleted;
int i, pos, n;



for (i=0; i < encrypted.length(); i++)
{
if((pos=decrypt.find(encrypted[i]))<0)
{
decrypt = decrypt + encrypted[i];
}

}

deleted = decrypt.substr(0,3);

decrypt.erase(0,3);

n=decrypt.find(deleted);

decrypt.erase(n,3); <----------------------------------------------------- error probably because of this

while(decrypt.find(deleted) != decrypt.npos){

n=decrypt.find(deleted);
decrypt.erase(n,3);

}
return decrypt;
}


assuming you passed l.pxyzl.ptol in, after you've gone through the first loop,

1
2
3
4
5
6
7
8
for (i=0; i < encrypted.length(); i++)
{
if((pos=decrypt.find(encrypted[i]))<0)
{
decrypt = decrypt + encrypted[i]; 
}

}


your function would've got rid of the second l.p in the string, so the string becomes: l.pxyztol. You then proceed to erase l.p, so the string becomes: xyztol.
Subsequent call to 'find' will return -1 since the substring isn't there anymore.

I don't think your first loop is doing what the spec is saying. If it was, then the second step in the spec is completely trivial.
Last edited on
decrypt.erase(n,3); <----------------------------------------------------- error probably because of this
Yes, because n will be -1 [string::npos] (you need to check that).

What you do is eliminating all second occurrence of a character no matter where. But I guess that you should eliminate all subsequent same characters?
Topic archived. No new replies allowed.