gpt4 book ai didi

c++ - 在我解开两个流之后,cin 导致 cout 刷新

转载 作者:行者123 更新时间:2023-11-30 02:57:00 25 4
gpt4 key购买 nike

我正在尝试了解 iostreams 关于 tie() 的行为。根据我的发现,下面的代码不应向屏幕输出任何内容。

    cin.tie(NULL);
int i;
cout << "TEST";
cin >> i;
while (true);

相反,它应该表现得像

    cin.tie(NULL);
int i;
cout << "TEST";
read(0, &i, sizeof(int));
while (true);

换句话说,cout 缓冲区在调用 cin 输入时被刷新,即使流是解开的。我尝试用 g++ 4.8.0 和 4.6.3 编译这段代码。我还尝试在 cin.tie(NULL) 之后调用 cin.tie(),它正确返回 NULL,因此不应绑定(bind)流。

还有我缺少的 tie() 吗?

最佳答案

您没有执行 cout.sync_with_stdio(false);,因此您的 std::cout 与 C I/O 同步,这意味着每个输出都被单独并立即发送到 C I/O 库调用,然后在您的情况下服从 glibc 的实现定义规则。

快速检查,this glibc manual提到了

...buffered output on a stream is flushed automatically:

  • Whenever an input operation on any stream actually reads data from its file.

(虽然这听起来并不令人信服,因为还没有从标准输入中读取任何内容..无论如何,cout.sync_with_stdio(false) 使这个 cin.tie(NULL) 测试用例在我的 Linux 上表现得像预期的那样)。

关于c++ - 在我解开两个流之后,cin 导致 cout 刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14991671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com