How to remove whitespace in a sentence using remove command in C++?
I get a file as input and I read the first line like this (quotes mark the begin and end, but are not in the file):
" 1, 2.0, 3.0, 4.0 "
When I use the remove command like this:
astring = line;
cout << endl << "Bef开发者_运维问答ore trim: " << line << endl;
remove(astring.begin(), astring.end(), ' ');
cout << endl << "After trim: " << astring << endl;
I got the output as:
1,2.0,3.0,4.02.0, 3.0, 4.0
I need the output as 1,2.0,3.0,4.0
only. What is the problem here?
std::remove
just moves all of the non-removed elements forward in the sequence; you then need to truncate the underlying container, using erase
:
s.erase(std::remove(s.begin(), s.end(), ' '), s.end());
This is called the erase-remove idiom. remove
cannot truncate the underlying container itself because it doesn't have a reference to the container; it only has iterators to elements in the container.
James was correct in his answer and it saved me a lot of work. td::remove just moves all of the non-removed elements forward in the sequence; you then need to truncate the underlying container, using erase:
std.erase(std::remove(s.begin(), s.end(), ' '), s.end()); This is called the erase-remove idiom. remove cannot truncate the underlying container itself because it doesn't have a reference to the container; it only has iterators to elements in the container.
精彩评论