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