Injecting string to 'cin'

Instead of screwing around with cin, you can have your program accept a general std::istream&. When running normally, just pass it cin. During a unit test, pass it an I/O stream of your own creation.


If you really, really want to use std::cin, try this:

int main() {
  using namespace std;
  streambuf *backup;
  istringstream oss("testdata");
  backup = cin.rdbuf();
  cin.rdbuf(oss.rdbuf());
  string str;
  cin >> str;
  cout << "read " << str;    
}

You can restore std::cin's streambuf when you are done from backup. I don't guarantee the portability of this ;P

Tags:

C++

Iostream