std std - 1 year ago 219
C++ Question

why do we need to tie cin and cout?

By default, the standard input device is tied together with the standard output device in the form:

std::cin.tie (&std::cout);
which guarantees that the output buffer has been flushed before input is invoked. So I try to untie them by using
, but it seems that the result, has no difference with the tied one.

using namespace std;

int main(int argc, char *argv[])
char c;

cin.tie(0); //sorry for my mistake!but it's not the point

cout << "Please enter c:";
cin >> c;
cout << c ;

return 0;

Am I testing wrong? Why do we need to tie them together? Do they share the same buffer?

Answer Source

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).

edit: 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download