为什么我们需要绑定cin和cout? [英] why do we need to tie cin and cout?

查看:991
本文介绍了为什么我们需要绑定cin和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); //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?

推荐答案

在你的例子中没有什么问题(除了你应该添加一个分号 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() cout cin ,不能保证 cout 被刷新。但是不能保证缓冲区也不是未刷新的。事实上,如果计算机有足够的资源,它会立即刷新 cout 缓冲区 ,所以这发生在 / code>要求输入。这是你的例子中的情况。

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

编辑:在理论上,如果绑定, cout可以共享相同的缓冲区。但是,我认为没有实现。一个原因是两个可能是不相关的()d。

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.

这篇关于为什么我们需要绑定cin和cout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆