samuraiseoul
samuraiseoul

Reputation: 2967

C++ string::erase deletes the entire string?

SO here in my function

string chopstring(string& tocut, List test[26]){
    string totoken = "";
    while(tocut[0] == ' ' || tocut[0] == 10 || tocut[0] == 13){
        tocut.erase(0);
    }
    int finish = 0;
    finish = tocut.find(" ", 0);
    if (finish == string::npos){
        cout << "NPOS!" << endl;
        for(int i = 0 ; i < 26; i++)
        test[i].Print();
    }
    for (int i = 0; i < finish; i++){
        totoken += tocut[i];
    }
    string::iterator start = tocut.begin();
    string::iterator end = tocut.begin() + totoken.length();
    tocut.erase(start, end);
    return tokenize(totoken);
}

Im having trouble with the string::erase. It deletes the entire string? Any suggestions? Id like to learn the reason too so please explain if you know.

it's being called in another function that stored the returned token in a linked list, then calls this function again untill the string (tocut) is empty. The first line it feeds in is "The Time Traveller (for so it will be convenient to speak of him)". What happens right now is that it takes the first "The", tokenizes it, and does it's thing, but the tocut.erase(start, end), deletes the whole string, and causes the program to crash.

Upvotes: 0

Views: 442

Answers (2)

jogojapan
jogojapan

Reputation: 69977

ArunMu is right. But if I am not mistaken, an additional problem is that when the function reaches string::npos it does not end. Instead it continues down to where the call to erase() is made, and erase(start,string::npos) deletes the entire rest of the string indeed.

Upvotes: 3

Arunmu
Arunmu

Reputation: 6901

Do below:

    while(tocut[0] == ' ' || tocut[0] == 10 || tocut[0] == 13){
        tocut.erase(0,1);   // see cpp reference. For single argument it takes iterator
    }

Upvotes: 4

Related Questions