Search code examples
c++http-redirectiostreamcinstreambuf

Is it possible to "prepare" input from cin?


In his answer, specifically in the linked Ideone example, @Nawaz shows how you can change the buffer object of cout to write to something else. This made me think of utilizing that to prepare input from cin, by filling its streambuf:

#include <iostream>
#include <sstream>
using namespace std;

int main(){
        streambuf *coutbuf = cout.rdbuf(cin.rdbuf());
        cout << "this goes to the input stream" << endl;
        string s;
        cin >> s;
        cout.rdbuf(coutbuf);
        cout << "after cour.rdbuf : " << s;
        return 0;
}

But this doesn't quite work as expected, or in other words, it fails. :| cin still expects user input, instead of reading from the provided streambuf. Is there a way to make this work?


Solution

  • #include <iostream>
    #include <sstream>
    
    int main()
    {
        std::stringstream s("32 7.4");
        std::cin.rdbuf(s.rdbuf());
    
        int i;
        double d;
        if (std::cin >> i >> d)
            std::cout << i << ' ' << d << '\n';
    }