Why do we need to tie std::cin and std::cout?

There is nothing wrong in your example (except that you should add a semi-colon after the cin.tie(0) line), nor with the way iostream objects work.

tie() simply guarantees the flushing of cout before cin executes an input. This is useful for the user to see the question before being asked for the answer.

However, if you un-tie() the cin from cout, there is no guarantee that the buffer of the cout is flushed. But there is no guarantee that the buffer is un-flushed neither. In fact, if the computer has enough resources, it will flush the cout buffer immediately, so this occurs before cin asking for the input. This is the case in your example.

So, everything works well. Except that after cin.tie(0), there is no guarantee that the flush-ing will occur. However, in 99% of the cases, that flush-ing will still occur (but it is no longer guaranteed).

In theory, if tied, cin and cout could share the same buffer. But, I think no implementation does that. One reason is that the two may be un-tie()d.

Leave a Comment