Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ why this error "basic_string::substr" and breaking up the loop

i am trying to get the last letters of a word, to compare if these letters row are in a vector. So i want to check first the last 2, then the last 3 and the last 4 letters. As soon as it finds one, it should break up, and return false. Else it should check everything left, and return in case of nothing founded, true.

This my function:

bool isIt(wstring word, vector <wstring> vec) {

int ct = 2;
while (ct < 5) {
    word = word.substr(word.length() - ct, word.length()-1);
    //wcout << word << endl;
    if (find(vec.begin(), vec.end(), word) != vec.end()) {
        //wcout << "false" << endl;
        ct = 5; return false;

    } else {ct++; wcout << ct << endl; continue; }
}  return true;}

the function get called thru this:

if( word >3){ isIt(word, vec); }

when the first check does fail, i receive this error msg:

terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::substr

i don't understand, why it does not continue, once it is in the else part. I hope my description was good enough. BR

like image 476
Ramis Habib Avatar asked May 21 '26 22:05

Ramis Habib


1 Answers

The bug is here, where you modify word.

    word = word.substr(word.length() - ct, word.length()-1);

If word is "ABCD" entering this function then the first time through the loop this evaluates to:

    word = std::string("ABCD").substr( 2, 3 );

And the second time through your loop it evaluates to:

    word = std::string("CD").substr( size_t(-1), 1 );
like image 116
Drew Dormann Avatar answered May 23 '26 13:05

Drew Dormann