Here is my simple code:
#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?
}
What I was thinking that above code will set cin‘s buffer to cout‘s buffer so when I will input some number it’ll will be outputted also. I guess I’m confused with my own program. Can anyone tell me what’s going on in the program?
Also, if I add one more line at end : std::cout<<foo; , then it prints random number which means foo never gets input. So what’s happening overall?
The stream is responsible for the formatting and delegates the IO to the streambuf (which thus do more than buffering, it executes the IO as well).
So with
std::cin.rdbuf(std::cout.rdbuf())you are asking to cin to do its input using the streambuf of cout, which probably is not ready for doing input. Sostd::cin>>foowill fail.