为什么我们需要将std :: cin和std :: cout绑定在一起?

问题描述:

默认情况下,标准输入设备与标准输出设备以以下形式捆绑在一起:
std :: cin.tie(& std :: cout); 保证在调用输入之前已经清空了输出缓冲区。因此,我尝试使用 std :: cin.tie(0)解除它们的束缚,但看来结果与被束缚的束缚者没有什么区别。

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 std::cin.tie(0), but it seems that the result, has no difference with the tied one.

#include<iostream>
using namespace std;

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

    cin.tie(0)

    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?

在您的示例中没有错(除了您应该在分号后添加分号) cin.tie(0)行),也不能使用iostream对象的工作方式。

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()仅保证在 cin 执行输入之前刷新 cout 。这对于用户在被问到答案之前先查看问题很有用。

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.

但是,如果您取消 tie() cin 来自 cout ,不能保证的缓冲区cout 已刷新。但是,不能保证缓冲区不会被清除。实际上,如果计算机有足够的资源,它将立即刷新 cout 缓冲区 ,因此这发生在 cin 要求输入。在您的示例中就是这种情况。

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.

因此,一切正常。除了在 cin.tie(0)之后,不能保证会发生冲洗。但是,在99%的情况下,冲洗仍然会发生(但不再保证)。

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

理论上,如果并列, cin cout 可以共享相同的缓冲区。但是,我认为没有实现可以做到。原因之一是两者可能是un-tie()d。

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.