是否有可能“准备”使用从cin输入? [英] Is it possible to "prepare" input from cin?

查看:79
本文介绍了是否有可能“准备”使用从cin输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

他的答案中,特别是在链接的Ideone示例,@ Nawaz显示了如何更改 cout 的缓冲区对象以写入其他内容。这让我想到了利用它来填充 streambuf

In his answer, specifically in the linked Ideone example, @Nawaz shows how you can change the buffer object of cout to write to something else. This made me think of utilizing that to prepare input from cin, by filling its streambuf:

#include <iostream>
#include <sstream>
using namespace std;

int main(){
        streambuf *coutbuf = cout.rdbuf(cin.rdbuf());
        cout << "this goes to the input stream" << endl;
        string s;
        cin >> s;
        cout.rdbuf(coutbuf);
        cout << "after cour.rdbuf : " << s;
        return 0;
}

但这并不像预期的那样有效,换句话说,失败。 :| cin 仍然希望用户输入,而不是从提供的 streambuf 中读取。

But this doesn't quite work as expected, or in other words, it fails. :| cin still expects user input, instead of reading from the provided streambuf. Is there a way to make this work?

推荐答案

#include <iostream>
#include <sstream>

int main()
{
    std::stringstream s("32 7.4");
    std::cin.rdbuf(s.rdbuf());

    int i;
    double d;
    if (std::cin >> i >> d)
        std::cout << i << ' ' << d << '\n';
}

这篇关于是否有可能“准备”使用从cin输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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