12

What is the correct way to remove the \0 char´s from a given string.

I´m trying with no success:

std::string msg(data); // Data comes from a remote system connected via socket...
msg.erase(std::remove(msg.begin(), msg.end(), '\0'), msg.end());

This gives compilation error:

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

datacomes from a remote system using socket, and contains several pieces of code numbers with /0 in the middle due to source logic.

Mendes
  • 17,489
  • 35
  • 150
  • 263

1 Answers1

8

Your problem arises from a missing #include directive. Your intention was to call std::remove() from <algorithm>, but you inadvertently called std::remove() from <cstdio>. So with

#include <algorithm>

it should work.

(IMHO std::remove(const char*) should be std::remove_file(std::string const&) or at least std::remove_file(const char*).)

Walter
  • 44,150
  • 20
  • 113
  • 196