Sunday, August 2, 2009

C++ a loop with string.erase !?

I want to get rid of all numbers in my sentence. This only gets rid of hte first number. What am I doing wrong in the loop?








#include %26lt;iostream%26gt;


#include %26lt;string%26gt;


#include %26lt;cctype%26gt;


using namespace std;





int main()


{


string myString="I have 24 bananas.";


size_t len = myString.length();





size_t i=0;


while (i%26lt;len)


{


if ( isdigit(myString[i]) )


(myString.erase(i,1));


++i;


}


cout %26lt;%26lt; myString%26lt;%26lt; endl;


return 0;


}

C++ a loop with string.erase !?
The other answers are generally on mark but the bottom line is that this is not the best erase() method to use in that kind of loop.





myString.erase(i, 1) actually returns a new string reference. You are ignoring the return value but the underlying string has still changed. You have to be careful with stl containers (which include std::string) that the container and its iterators aren't invalidated with operations that mutate the state.





I think the single iterator form of string::erase() is a better choice for what you are doing. Something like:





string::iterator it = myString.begin();





while (it != myString.end())


{


if (isdigit(*it))


it = myString.erase(it);


else


it++;


}
Reply:The 2 and 4 are beside each other. When you erase the letter, all letters after that are shifted back a space. You're saying ++i so it skips one. It's a bit dificult to explain but you'll see it happen if you use:


cout %26lt;%26lt; myString[i];





Basically, fix it by saying:


if ( isdigit(myString[i]) )


{


(myString.erase(i,1));


i -= 2;


}


++i;








I think you might get away with simply --i but I'm not sure. Hope that helps :)
Reply:I have updated the code to properly erase all digits





#include %26lt;iostream%26gt;


#include %26lt;string%26gt;


#include %26lt;cctype%26gt;


using namespace std;





int main()


{


string myString="I have 24 bananas.";


size_t len = myString.length();





size_t i=0;


while (i%26lt;len)


{


if ( isdigit(myString[i]) )


(myString.erase(i,1)); // erase one character, leave 'i' alone.


else //* This is what I added *//


++i; // advance to next character


}


cout %26lt;%26lt; myString%26lt;%26lt; endl;


return 0;


}


No comments:

Post a Comment