streambuf filter

S

steve.holle

Can anyone provide me with a simple example of a streambuf filter for
character substitution that would function like this :
fout << filter << fin

All the filter would need to do is replace a specific character with
another.

Thanks for your help.
 
T

Tilman Kuepper

Hello Steve,
Can anyone provide me with a simple example of a
streambuf filter for character substitution that would
function like this :
fout << filter << fin

Try this one:

#include <sstream>
#include <istream>
#include <iostream>

class ReplaceBuf : public std::streambuf
{
char readBuf_; // current char
std::streambuf* pExternBuf_; // source buffer

// get next input char
int_type underflow()
{
if(gptr() == &readBuf_)
return traits_type::to_int_type(readBuf_);

int_type nextChar = pExternBuf_->sbumpc();
if(nextChar == EOF) return traits_type::eof();
readBuf_ = traits_type::to_char_type(nextChar);

// replace character
if(readBuf_ == 'X') readBuf_ = 'O';

setg(&readBuf_, &readBuf_, &readBuf_ + 1);
return traits_type::to_int_type(readBuf_);
}

public:
ReplaceBuf(std::streambuf* pExternBuf)
: pExternBuf_(pExternBuf)
{
setg(0, 0, 0);
}
};


int main()
{
std::stringstream test("HELLX WXRLD, TEST...!");
ReplaceBuf rbuf(test.rdbuf());
std::istream strm(&rbuf);

std::string line;
std::getline(strm, line);
std::cout << line << "\n";
}

Best regards,
Tilman
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top