将字符串注入“cin” [英] Injecting string to 'cin'

查看:140
本文介绍了将字符串注入“cin”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数从std :: cin读取用户输入,我想写一个单元测试,将一些字符串插入std :: cin,这样以后从std :: cin中的提取将读取该字符串而不是暂停对于键盘输入。

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 read that string instead of pausing for keyboard input.

理想情况下,我将更改函数签名,以便我可以传递自定义istream作为参数,但我不能这样做,固定接口,我不能更改。

Ideally, I would change the function signature so that I can pass a custom istream as parameters, but I can't do that here since I have a fixed interface that I cannot change.

cin.putback()几乎是我想要的,但它一次只插入一个字符,它是以相反的顺序插入它们(但我读的地方,放回原来不是原来的字符可以是危险的,虽然网站没有详细说明为什么)。我试过几种方法将字符串注入cin的内部缓冲区cin.rdbuf(),但没有一个工作。我也考虑使用外部测试脚本或创建子进程,但我想先考虑一个纯C ++的测试。

cin.putback() is almost what I wanted, however it is inserting only one character at a time, and it is inserting them in reverse order (but I read somewhere that putting back char that wasn't originally there can be dangerous, though the website doesn't elaborate why). I've tried several methods to inject the string to cin's internal buffer cin.rdbuf(), but none would work either. I've also considered using an external testing script or creating subprocess, however I'd like to first consider a test in pure C++.

所以,有没有任何方法把字符串放到cin?或者你知道更好的方式注入我的假键盘输入?

So, is there any method to put strings into cin? Or do you know a better way to inject my "fake keyboard input"?

推荐答案

如果真的,真的想使用std :: cin,try this:

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;    
}

从备份完成后,可以恢复std :: cin的streambuf。
我不保证这个的可移植性; P

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

这篇关于将字符串注入“cin”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆