Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ How to remove \0 char from std::string

Tags:

c++

stdstring

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.

like image 852
Mendes Avatar asked Dec 03 '15 13:12

Mendes


1 Answers

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*).)

like image 57
Walter Avatar answered Sep 28 '22 04:09

Walter