简体   繁体   中英

Infinite loop with string iterator in C++

While i'm willing to parse instructions contained in strings, I am basically trying to clean a string from it's spaces and tabs character, in order to seek instructions in it. Unfortunately, my loop is going into an infinite loop, and I can't find why as i'm refreshing the iterator on each erasing of a char...

Any Help please?

void  myClass::parseInstructions(std::string& line)
{
    std::string::iterator        it;

    for (it = line.begin(); it != line.end(); ++it)
        if (((*it) == ' ') || ((*it) == '\t'))
            it = line.erase(it);
}

The flow of your code:

it = line.begin(); 
while (it != line.end()) {
    if (((*it) == ' ') || ((*it) == '\t'))
        it = line.erase(it);
    ++it;
}

Correct code:

it = line.begin(); 
while (it != line.end()) {
    if (((*it) == ' ') || ((*it) == '\t'))
        it = line.erase(it);
    else // <---- THIS IS IMPORTANT
        ++it;
}

Right now you'll miss two whitespace characters in a row, and when the final character is whitespace you'll move right past the end.

Or you could just use std::remove_copy_if , which should have much lower complexity.

C++0x solution:

void  myClass::parseInstructions(std::string& s)
{
      std::string::iterator end = std::remove_if(s.begin(),s.end(),[](char c){ return c==' ' || c == '\t'; });
      s.erase(end, s.end());
}

Demo in which removing only a : http://www.ideone.com/hgnCN


C++03 Solution

bool predicate(char c) { return c==' ' || c == '\t'; }
void  myClass::parseInstructions(std::string& s)
{
      std::string::iterator end = std::remove_if(s.begin(),s.end(),predicate);
      s.erase(end, s.end());
}

Demo in which removing r now : http://www.ideone.com/W5unx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM