C++ - 为什么 fflush(stdout) 不适用于 iostream?

标签 c++ iostream stdio fflush

我正在阅读 freopen()并意识到如果我们为其指定 stdin/stdout,即使我们使用 cin/cout 进行编码,该函数也能正常工作。

稍微研究一下,我找到了这个链接 freopen() equivalent for c++ streams ,其中一位用户回答:

From C++ standard 27.3.1:
"The object cin controls input from a stream buffer associated with the object stdin, declared in <cstdio>."

So according to the standard, if we redirect stdin it will also redirect cin. Vice versa for cout.

在 CPPReference 上也看到了类似的东西:
http://en.cppreference.com/w/cpp/io/cin
http://en.cppreference.com/w/cpp/io/cout

The global objects std::cout and std::wcout control output to a stream buffer of implementation-defined type (derived from std::streambuf), associated with the standard C output stream stdout.

这就是它有点令人困惑的地方,因为我也在阅读有关刷新的内容并注意到 fflush(stdout) 根本无法与 cin/cout 一起工作。

例如,此示例代码不会打印任何内容:

#include <cstdio>
#include <iostream>

using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n;
    cout << "Please, enter a number: \n";
    fflush(stdout);
    cin >> n;
}

虽然下面的代码将打印到 output.txt:

#include <cstdio>
#include <iostream>

using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    freopen("output.txt", "w", stdout);

    cout << "Some string";
    while (true);
}

删除 ios::sync_with_stdio(false);从第一个示例代码来看,它的行为符合预期。和 freopen()无论如何都可以工作(有或没有它)。

所以问题是:为什么 fflush(stdout) 不适用于 iostream,而 freopen(..., stdout) 有效?也许,这个问题可以更深入:cin/cout 与 stdin/stdout 关联的扩展名是什么?

抱歉发了这么长的帖子。我尽量做到详细和简洁。

我希望这是可以理解的。

提前致谢。

附言:我输入了ios::sync_with_stdio(false);cin.tie(0);故意的。

最佳答案

我的第一个问题是“您为什么要这样做”?有一个std::ostream::flush()为此目的的功能,所以使用它,例如cout.flush();

它“不起作用”的原因是用 fflush(FILE* f) 刷新的缓冲区与用于 std::ostream 的缓冲区不同 (或者至少不能保证它会是)。 std::ostream::flush() 很可能会在作为实现一部分的基础文件对象上调用 fflush(FILE*)

关于C++ - 为什么 fflush(stdout) 不适用于 iostream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41776514/

相关文章:

C sscanf() 强制数字输入

c - 如何像 ghostscript 一样将 X11 键盘事件路由到标准输入?

c++ - 如何确保在关闭 fstream 之前将数据写入磁盘?

c++ - C++ 可以通过添加一些东西而不删除所有以前的上下文来处理记事本输入文件吗?

c++ - 在 C++ 中使用 "+"连接字符串

文件流 : when to check for error? 的 C++ 操作

c++ - 使用 iostream 消失的段错误

c - 如何停止输入换行符

c++ - 更改非 Windows 应用商店应用程序的磁贴颜色?

c++ - istream_iterator,黑魔法?