Search code examples
c++stringerase

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.


Solution

  • Do below:

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