Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Created February 6, 2014 21:48
Show Gist options
  • Save dgodfrey206/8853181 to your computer and use it in GitHub Desktop.
Save dgodfrey206/8853181 to your computer and use it in GitHub Desktop.
Reversing the content of an input stream.
#include <iostream>
#include <sstream>
#include <vector>
#include <iterator>
template<class charT>
class reverse_buffer : public std::basic_stringbuf<charT>
{
typedef std::basic_stringbuf<charT> streambuf_type;
typedef typename streambuf_type::int_type int_type;
typedef typename streambuf_type::traits_type traits_type;
public:
reverse_buffer(std::basic_streambuf<charT>* sbptr)
{
std::basic_ostringstream<charT> buf;
buf << sbptr;
std::basic_string<charT> rev = buf.str();
std::copy(rev.rbegin(), rev.rend(), std::ostreambuf_iterator<charT>(&sb));
}
int_type underflow()
{
ch = traits_type::to_char_type(sb.sbumpc());
this->setg(&ch, &ch, &ch + 1);
return ch;
}
private:
charT ch;
streambuf_type sb;
};
std::istringstream iss("hello world how are you?");
int main()
{
reverse_buffer<char> rbuf(iss.rdbuf());
std::istream is(&rbuf);
std::vector<std::string> v;
std::istream_iterator<std::string> beg(is), end;
std::copy(beg, end, std::back_inserter(v));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment