Is it possible to "prepare" input from cin?
Asked Answered
I

2

4

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?

Innerdirected answered 16/5, 2011 at 5:51 Comment(2)
Are you asking how to filter cin?Nolannolana
@Gabe: Uhm, nope, I want to provide a prepared input to cin, so it doesn't expect user input but rather reads from the provided content.Innerdirected
S
4
#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';
}
Scullery answered 16/5, 2011 at 6:15 Comment(2)
Eww, I should've waited 5 min. :(Innerdirected
@Xeo: I thought the same when I posted :-).Scullery
I
3

Disregard that question, while further investigating it, I made it work. What I did was actually the other way around than planned; I provided cin a streambuf to read from instead of filling its own.

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

int main(){
  stringstream ss;
  ss << "Here be prepared input for cin";
  streambuf* cin_buf = cin.rdbuf(ss.rdbuf());
  string s;
  while(cin >> s){
    cout << s << " ";
  }
  cin.rdbuf(cin_buf);
}

Though it would still be nice to see if it's possible to provide prepared input without having to change the cin streambuf directly, aka writing to its buffer directly instead of having it read from a different one.

Innerdirected answered 16/5, 2011 at 6:11 Comment(1)
Changing the streambuf is the right solution, not trying to modify cin's existing streambuf.Mahout

© 2022 - 2024 — McMap. All rights reserved.