【问题标题】:Is it possible to "prepare" input from cin?是否可以“准备”来自 cin 的输入?
【发布时间】:2011-08-26 04:46:02
【问题描述】:

his answer 中,特别是在linked Ideone example 中,@Nawaz 展示了如何更改cout 的缓冲区对象以写入其他内容。这让我想到利用它来准备来自cin 的输入,通过填写其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 中读取。有没有办法让这个工作?

【问题讨论】:

  • 你是问如何过滤cin
  • @Gabe:嗯,不,我想为 cin 提供一个准备好的输入,所以它不需要用户输入,而是从提供的内容中读取。

标签: c++ redirect iostream cin streambuf


【解决方案1】:
#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';
}

【讨论】:

  • Eww,我应该等 5 分钟。 :(
  • @Xeo:我发帖时也是这么想的 :-)。
【解决方案2】:

忽略这个问题,在进一步调查它的同时,我让它工作了。我所做的实际上与计划相反。我提供了cin 一个streambuf 来读取而不是自己填充。

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

int main(){
  stringstream ss;
  ss << "Here be prepared input for cin";
  streambuf* cin_buf = cin.rdbuf(ss.rdbuf());
  string s;
  while(cin >> s){
    cout << s << " ";
  }
  cin.rdbuf(cin_buf);
}

尽管看看是否可以提供准备好的输入而无需直接更改 cin streambuf 还是很不错的,也就是直接写入其缓冲区而不是从另一个缓冲区读取。

【讨论】:

  • 更改streambuf是正确的解决方案,而不是试图修改cin现有的streambuf。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-05
  • 2012-01-24
相关资源
最近更新 更多