Injecting string to 'cin'

前端 未结 3 1944
长发绾君心
长发绾君心 2020-12-09 17:36

I have a function that reads user input from std::cin, and I want to write a unittest that inserts some strings into std::cin, such that later extraction from std::cin will

相关标签:
3条回答
  • 2020-12-09 17:51

    cin.putback() is guaranteed to work with at most one character, so you can't putback a whole string. Use a stream that wraps cin and allows arbitrary putback() sequence length. I think Boost.Iostream have something similar, and if it doesn't then it might be helpful to implement such a wrapper.

    0 讨论(0)
  • 2020-12-09 17:56

    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.

    0 讨论(0)
  • 2020-12-09 17:57

    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

    0 讨论(0)
提交回复
热议问题