Search code examples
c++copyistream

C++ Extract the contents of an istream and copy to another


I was wondering how I would go about sucking out the contents of one istream and saving it in another istream. It seems explicit copying doesn't seem to work for streams, so I was wondering if this could be achieved instead.


Solution

  • Looks like you just want a change buffers:

    int main()
    {
        std::istream copy(nullptr);
        copy.rdbuf(std::cin.rdbuf());
        std::cin.rdbuf(nullptr);
    
        for (std::string word; copy >> word; ) {
            std::cout << word << ' ';
        }
    }