Enz*_*ura 2 c++ iostream stdio fflush
我正在阅读freopen()并意识到,如果我们为其指定 stdin/stdout,即使我们使用 cin/cout 进行编码,该函数也将起作用。
研究了一下,我发现这个链接 freopen() 相当于 c++streams,其中一位用户回答:
来自 C++ 标准 27.3.1:
“该对象cin控制来自与该对象关联的流缓冲区的输入stdin,在 中声明<cstdio>。”
所以根据标准,如果我们重定向stdin它也会重定向cin。反之亦然cout。
在 CPPReference 上也看到了类似的内容:
http://en.cppreference.com/w/cpp/io/cin
http://en.cppreference.com/w/cpp/io/cout
全局对象 std::cout 和 std::wcout 控制输出到实现定义类型(派生自 std::streambuf)的流缓冲区,与标准 C 输出流 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;
}
Run Code Online (Sandbox Code Playgroud)
下面的代码将打印到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);
}
Run Code Online (Sandbox Code Playgroud)
从第一个示例代码中删除后ios::sync_with_stdio(false);,它的行为符合预期。无论如何都freopen()可以工作(无论有没有它)。
所以问题是:为什么 fflush(stdout) 不能与 iostream 一起使用,而 freopen(..., stdout) 可以工作?也许,这个问题可以变得更深入:cin/cout 与 stdin/stdout 关联到什么扩展?
抱歉发了这么长的帖子。我尝试尽可能详细和简洁。
我希望这是可以理解的。
提前致谢。
PS:我是故意放ios::sync_with_stdio(false);的cin.tie(0);。
我的第一个问题是“你为什么想要”?有一个std::ostream::flush()用于此目的的函数,因此请使用该函数,例如cout.flush();。
它“不起作用”的原因是刷新的缓冲区与fflush(FILE* f)所使用的缓冲区不同std::ostream(或者至少不能保证它会是)。它很可能确实std::ostream::flush()调用fflush(FILE*)了作为实现一部分的底层文件对象。
| 归档时间: |
|
| 查看次数: |
4584 次 |
| 最近记录: |