Post

How to temporarily redirect std::cin from a std::stringstream

This is nice for testing methods that rely on std::cin programatically:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <sstream>

int main()
{
   // Prepare fake stringstream
   std::stringstream fake_cin;
   fake_cin << "Hi";

   // Backup and change std::cin's streambuffer
   std::streambuf *backup = std::cin.rdbuf(); // back up cin's streambuf
   std::streambuf *psbuf = fake_cin.rdbuf(); // get file's streambuf
   std::cin.rdbuf(psbuf); // assign streambuf to cin

   // Read something, will come from out stringstream
   std::string input;
   std::cin >> input;

   // Verify that we actually read the right text
   std::cout << input << std::endl;

   // Restore old situation
   std::cin.rdbuf(backup); // restore cin's original streambuf
}
This post is licensed under CC BY 4.0 by the author.