How to strip newlines from a char-array?

c++, char, pointers

Solution

#include <algorithm>
size = std::remove(pData, pData + size, '\n') - pData;
pData[size] = 0; // optional

For some C++11 lambda fun:

#include <algorithm>
size = std::remove_if(pData, pData + size, [](char c) { return c == '\n'; }) - pData;
pData[size] = 0; // optional

Problem

I've put the contents of a file in a char-array using this function: ``` void Read::readFile(){ FILE * fp = fopen(this->filename,"rt"); fseek(fp, 0, SEEK_END); long size = ftell(fp); fseek(fp, 0, SEEK_SET); char *pData = new char[size + 1]; fread(pData, sizeof(char), size, fp); fclose(fp); this->data = pData; } ``` Now I want to strip all line-endings from the char-array. How do I do this without casting the char-array into a string first? btw. this is part of a homework where we aren't allowed to use the string-library.

Original source