混淆在rdbuf()

M3t*_*0it 4 c++

这是我的简单代码:

#include <iostream>
int main()
{
    int foo;
    std::cin.rdbuf(std::cout.rdbuf());
    std::cin>>foo; // what'll happen at this line? whatever I'll input will go to cout's buffer then to foo , right?
}
Run Code Online (Sandbox Code Playgroud)

我以为上面的代码会将cin缓冲区设置为cout缓冲区,所以当我输入一些数字时它也会被输出.我想我对自己的程序感到困惑.谁能告诉我程序中发生了什么?

另外,如果我在结尾添加一行:std::cout<<foo;,那么它会打印随机数,这意味着foo永远不会得到输入.那么整体上发生了什么?

APr*_*mer 6

流负责格式化并将IO委托给streambuf(因此不仅仅是缓冲,它还执行IO).

因此,std::cin.rdbuf(std::cout.rdbuf())你要求cin使用cout的streambuf进行输入,这可能还没有准备好做输入.所以std::cin>>foo会失败.