Search code examples
c++erase-remove-idiom

Erase remove idiom on a std::string with non-printable characters throws exception


I am reading some text from another process through a pipe. The pipe returns the data to the variable chBuf but contains lots of non-printable chars. I tried to remove these non-printable characters using erase and remove but throws an exception. The program works without this erase remove line. What may I doing wrong?

 ReadFile(si->child_out_r, chBuf, BUFSIZE, &dwRead, NULL);
 string s(chBuf);
 s.erase(remove_if(s.begin(), s.end(), [](char c) { return !isprint((unsigned)c); }), s.end());
 cout << s;

Solution

  • If the data in your file may contain nulls (amidst other characters that you're interested in), or it is not guaranteed to have a null at the very end, then you need to tell std::string how much data it should use to build the string. You do this with the std::string( const char *, size_t ) constructor:

    std::string  s( chBuf, dwRead );
    

    The string cleaning process should work OK if you do that.