Here are two useful little functions:
template<class C, class F>
bool remove_erase_if( C& c, F&& f ) {
using std::begin; using std::end;
auto it = std::remove_if( begin(c), end(c), std::forward<F>(f) );
if ( it == c.end())
return false;
c.erase( it, c.end() );
return true;
}
template<class C, class T>
bool remove_erase( C& c, T&& t ) {
using std::begin; using std::end;
auto it = std::remove( begin(c), end(c), std::forward<T>(t) );
if ( it == c.end())
return false;
c.erase( it, c.end() );
return true;
}
these both take a container, and either a test or an element.
They then remove and erase any elements that pass the test, or equal the element.
Your code emulated the remove
part of the above code, and did not do the erase
part. So the characters remaining at the end ... remained.
remove
(or your code) simply moves all the "kept" data to the front of the container. The stuff left over at the end ... stays there. The erase
step then tells the container that the stuff after the stuff you kept should be discarded. If you don't discard it, it ... remains ... and you get your bug.
With the above two functions, you can do this:
int main() {
std::string s = "What is your name?";
remove_erase( s, ' ' );
std::cout << s << '\n';
}
and you are done.
As an aside, using namespace std;
is often a bad idea. And std::endl
forces a buffer-flush, so I prefer '\n'
. Finally, system("pause")
can be emulated by running your IDE in a mode that leaves you your command window open, instead of adding it to your code Ctrl-F5.