Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace some characters from stringstream in C++?

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.

like image 405
satyanarayana Avatar asked Nov 21 '25 03:11

satyanarayana


1 Answers

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'
like image 162
David G Avatar answered Nov 22 '25 17:11

David G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!