如何将数据放在cin从字符串 [英] How to put data in cin from string

查看:498
本文介绍了如何将数据放在cin从字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写测试(使用google测试框架)小型研究程序,而不是我写的。 (它只是一个小的控制台游戏,可以从命令行获取模式或只是得到它在运行时)
有一个问题:我不能更改souce代码,但几乎所有的方法使用cout和cin。我的问题是如何在测试(如从字符串获取数据的情况下)程序的请求(cin)回答?

I need to write tests(using google testing framework) for small study program that was written not by me. (it's just small console game which can get modes from command line or just get it in runtime) There is a problem: I can't change the souce code but there is in almost all methods used cout and cin. and my question is "how to answer on requests (cin) of programm while testing (something like get data for cin from string )?".

推荐答案

假设您可以控制 main()调用函数前测试)你可以改变 std :: cin 读取 std :: cout 写入:

Assuming you can control main() (or some other function called before the functions to be tested) you can change where std::cin reads from and where std::cout writes to:

int main(int ac, char* av[]) {
    std::streambuf* orig = std::cin.rdbuf();
    std::istringstream input("whatever");
    std::cin.rdbuf(input.rdbuf());
    // tests go here
    std::cin.rdbuf(orig);
}

(同样 std :: cout

此示例保存 std :: cin 的原始流缓冲区,然后离开 main()。然后设置 std :: cin 从字符串流中读取。它也可以是任何其他流缓冲区。

This example saves the original stream buffer of std::cin so it can be replaced before leaving main(). It then sets up std::cin to read from a string stream. It can be any other stream buffer as well.

这篇关于如何将数据放在cin从字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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