gpt4 book ai didi

c++ - 是否可以从 cin 输入 "prepare"?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:32:04 25 4
gpt4 key购买 nike

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 中读取。有什么办法可以做到这一点吗?

最佳答案

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

关于c++ - 是否可以从 cin 输入 "prepare"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6013638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com