Confusingly in rdbuf ()

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 buffer then to foo , right? } 

What I thought about the above code would set the cin buffer in the cout buffer, so when I enter some number, it will also be output. I guess I'm confused by my program. Can someone tell me what is going on in the program?

Also, if I add another line to the end: std::cout<<foo; then it prints a random number, which means that foo is never entered. So what is going on as a whole?

+4
source share
2 answers

The stream is responsible for formatting and delegates IO streambuf (which, therefore, does more than buffering, it also does IO).

So, with std::cin.rdbuf(std::cout.rdbuf()) you ask cin to do its input using streambuf cout, which is probably not ready for input. Thus, std::cin>>foo will fail.

+6
source

I think, but not sure, the reason why foo is not entered is because after you set cin buffer to cout, the line

 std::cin >> foo; 

will actually become

 std::cout >> foo; 

in which using the → operator is wrong, so nothing happens with foo.

Then when you use

 std::cout << foo; 

it will output foo, which will not be initialized, therefore a random number.

0
source

Source: https://habr.com/ru/post/1388610/


All Articles