Is it possible to “prepare” input from cin?

后端 未结 2 466
情歌与酒
情歌与酒 2021-01-13 22:15

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 thi

2条回答
  •  孤街浪徒
    2021-01-13 22:35

    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 
    #include 
    #include 
    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.

提交回复
热议问题