2

My question is similar to this, except that I'm dealing with wstring rather than string. I switched the types to wstring and wchar_t and compiled it but I'm getting an error. This is the code:

int delete_punc(std::wstring& str)
{
    wchar_t* chars = L".,!?";
    for (int i = 0; i < sizeof(chars); i++)
        str.erase(std::remove(str.begin(), str.end(), chars[i]), str.end());

    return 0;
}

This is the error that I get:

error: cannot convert ‘std::basic_string<wchar_t>::iterator
{aka __gnu_cxx::__normal_iterator<wchar_t*, std::basic_string<wchar_t> >}’
to ‘const char*’ for argument ‘1’ to ‘int remove(const char*)

Edit: I also tried other brute force variants. Both returned the same error.

int delete_punc(std::wstring& str)
{
    //str.erase(std::remove(str.begin(), str.end(), L"."), str.end());
    //str.erase(std::remove(str.begin(), str.end(), "."), str.end());
    return 0;
}
Community
  • 1
  • 1

1 Answers1

3

It looks like you forgot to #include <algorithm>, so the compiler could find only this overload.

More substantial errors in your code - you are using a pointer when you don't need to, which leads to the common sizeof(pointer) mistake, signed/unsigned comparison warning.

You are also calling std::string::erase in a loop, which might trigger more reallocations and character copying than you'd get with std::erase and std::remove_if with a lambda and std::any_of with a std::wstring. Try that instead.

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
  • It finally worked after including ``algorithm`` and changing the code to this form: ``str.erase(std::remove(str.begin(), str.end(), L'.'), str.end());``. Thank you – Hello Universe Feb 25 '17 at 11:54