Search code examples
c++iostreamifstreamerase-remove-idiom

C++ removing non-alphabetic chars from beginning of a word


I have the following code in a method of string type which reads words from a file, removes all non-alphabetic chars (as shown below) from the beginning of the word and returns them after it does so. After printing out the results in the main method, I have noticed that even though it should remove all the non-alphabetic characters from the beginning, it always still prints out 1, For example: The list contains the words:

There ,--once was a cute -;little rabbit and he got shot, end of story

After applying the function, the output was:

There -once was a cute ;little rabbit and he got shot, end of story

inFile >> word;
    for(int i=0; i<word.size(); i++){
        if(word[i] >= 'A' && word[i] <= 'Z' || word[i] >= 'a' && word[i] <= 'z')  break;
        else word.erase(i,1);
    }
    return word;

I would appreciate if someone could tell me just what the hell it is that i'm failing to see. I've tried all different functions e.g. Erase(), isalpha() etc. They all produce the same result when it shouldn't. What am I doing that is forbidding the last non-alphabetic character (at the beginning of a word) from being removed? I tried the same to remove all punctuation marks at the end of a word but it would remove all except for one (again).

Thanks for your time


Solution

  • Your loop skips characters since you remove an item and continue. If you remove, you have to decrease i because the next letter is at the same position after erasing. Or you have to have a while loop for each position erasing that position until it is alpha or end, but decreasing i is simpler and less error prone.

    Running the code on a debugger would've shown this problem in the logic immediately.