我可以停止std :: cout flushing on“\\\<br/>”? [英] Can I stop std::cout flushing on &quot;\n&quot;?

查看:121
本文介绍了我可以停止std :: cout flushing on“\\\<br/>”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这篇文章 std :: cout will当它附加到交互式设备(例如终端窗口)时,自动刷新 \\\
。否则(例如,当被管道传递到文件时),它将充分缓冲并只在 .flush() std :: endl

According to to this post std::cout will automatically flush on \n when it is attached to an interactive device (e.g. a terminal window). Otherwise (e.g. when being piped to a file) it will act fully buffered and will only flush on .flush() or std::endl.

有没有办法在Microsoft Visual C ++中覆盖此行为,以便我可以选择是否需要完全缓冲或行缓冲模式? p>

Is there a way to override this behaviour in Microsoft Visual C++ so that I can select whether I want fully buffered or line buffered mode?

推荐答案

与anon的(2009年4月28日)答案相反,这个行为与操作系统或控制台软件无关。

Contrary to anon's (Apr 28 '09) answer, this behavior has nothing to do with the operating system or "console software."

C ++的< iostream> 流设计为可与C的< stdio .h> 流。目标是允许使用 std :: cout printf / puts 。为了实现这一点, cd> stdout c实现 std :: cout ' streambuf code> stream。实际上,当标准输出附加到终端设备时,C的 stdout 是行缓冲的。

C++'s <iostream> streams are designed to be interoperable with C's <stdio.h> streams. The goal is to allow uses of std::cout to be intermixed with uses of printf/puts. To achieve this, std::cout's streambuf is implemented atop C's stdout stream. It is actually C's stdout that is line-buffered when the standard output is attached to a terminal device.

可以调用 std :: ios_base :: sync_with_stdio(false) (在您的程序使用任何C ++的标准I / O流之前)告诉C ++流库与底层文件描述符直接通信,而不是在C的流库上层。这避免了C的 stdout 流,并加速了C ++的I / O流,但是两个库不再混用。

You can call std::ios_base::sync_with_stdio(false) (before your program uses any of C++'s standard I/O streams) to tell the C++ streams library to communicate directly with the underlying file descriptors rather than layering atop C's streams library. This avoids C's stdout stream entirely and speeds up C++'s I/O streams at the cost of the two libraries no longer mixing well.

另一种方法是通过调用 stdout 设置为完全缓冲c / setvbufrel =nofollow> std :: setvbuf(stdout,nullptr,_IOFBF,BUFSIZ) 。然后,即使 std :: cout 仍在通过 stdout 写入,您将不会有 stdout 在每个换行符后刷新。

An alternative is to unconditionally set stdout to fully buffered by calling std::setvbuf(stdout, nullptr, _IOFBF, BUFSIZ). Then, even though std::cout is still writing through stdout, you will not have stdout flushing after every newline.

这篇关于我可以停止std :: cout flushing on“\\\<br/>”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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