i have a string. I want to delete the last character of the string if it is a space.
i tried the following code,
str.erase(remove_if(str.begin(), str.end(), isspace), str.end());
but my g++ compiler gives me an error saying:
error: no matching function for call to ‘remove_if(__gnu_cxx::__normal_iterator<char*,
std::basic_string<char, std::char_traits<char>, std::allocator<char> > >,
__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>,
std::allocator<char> > >, <unresolved overloaded function type>)’
please help.
The first problem is that
isspacehas multiple overloads in the C++ Standard Library. The initial fix is to provide an explicit type for the function so that the compiler knows which function to take the address of:It’s a big ugly but, hey, this is C++.
Second, your code will remove all spaces in the string, which is not what you seem to want. Consider a simple if statement on the last character of the string:
Hope this helps.