Reputation: 379
I have a requirement to replace all the carriage returns/ Line feeds from a stringstream in a VC++ Project. I am very new to this and I tried the following:
strCustData.Replace("\r\n","")
But this is not working because strCustData
is of type stringstream, not string. Please help me out in achieving this.
Upvotes: 3
Views: 7078
Reputation: 96810
You probably want to use a stream buffer to filter out the characters:
class filter : public std::streambuf
{
public:
filter(std::ostream& os) : m_sbuf(os.rdbuf()) { }
int_type overflow(int_type c) override
{
return m_sbuf->sputc(c == '\r' ? traits_type::eof() : c);
}
int sync() override { return m_sbuf->pubsync() ? 0 : -1; }
private:
std::streambuf* m_sbuf;
};
Now you can use it like this:
filter f(strCustData);
std::ostream os(&f);
os <<"\r\n"; // '\n'
Upvotes: 4
Reputation: 2054
An ugly (memory duplicating because of using a std::string
as buffer) way to do it is something like this:
// replace "foo" with "bar"
std::stringstream myStringStream("foobarfoobar");
std::string myString(myStringStream.str());
size_t start = 0;
while ((start = myString.find("foo", start)) != std::string::npos) {
myString.replace(start, strlen("foo"), "bar");
}
myStringStream.str(myString);
Upvotes: 2
Reputation: 16476
You need to convert the stringstream
into a std::string
- not CString like you seemingly tried to. std::string
has lots of functions that can be used to manipulate the characters.
Something like this (untested):
std::istringstream stream;
std::string str(stream.str());
std::replace(str.begin(), str.end(), '\r', ' ');
std::replace(str.begin(), str.end(), '\n', ' ');
You could probably collapse the two replaces into one, but I am writing off the top of my head.
Upvotes: 1