告诉`endl`不要刷新 [英] Tell `endl` not to flush

查看:104
本文介绍了告诉`endl`不要刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序打印大量短线到 cout



线看起来有点像这样:

  cout<<变量的值是:< endl; 

我想让程序快速运行 endl 正在杀死我,因为它在每次使用

$ b时启动 cout
$ b

现在,互联网上的一些人说我可以这样做:

  cout ;<变量的值是:<< variable<<\\\
;

但这似乎不是一个好的解决方案,因为 endl 抽象可以指定结束行的特定系统特定方法,其中 \\\
不指定。这也似乎是一个很差的解决方案,因为,如果我需要缓冲在未来,我将修改整个代码库。



因此,我问,是有一种禁用 endl



EDIT p>

进一步挖掘似乎表示 endl \ n 尊重操作系统可能选择结束其行的各种方式。 看起来似乎输出流检测到它是否处于潜在的互动情况和缓冲区和刷新。因此:问题可以通过手动告诉输出流执行主动缓冲...如果我能找出如何做到这一点可以解决。

解决方案


endl抽象了可以指定结束行的特定系统方式,其中\\\
不是。


std :: endl 定义为输出'\\\
'
正确的抽象系统特定的换行东西只是'\\\
'



防止刷新,一个只是不使用 std :: endl 。此外,标准输出可以是行缓冲的,如果它是或可以连接到交互式设备,在这种情况下,换行符将刷新流。如果这是一个问题,使用 ofstream 连接到一个命名文件我认为在类Unix系统行缓冲只发生时标准输出是一个终端。


My program prints a large number of short lines to cout.

As a slightly contrived example, my lines look a little like this:

cout<<"The variable's value is: "<<variable<<endl;

I'd like the program to run fast and I do believe that endl is killing me because it initiates a buffer flush on cout every time it is used.

Now, some folks on the internet have said that I could do this instead:

cout<<"The variable's value is: "<<variable<<"\n";

But this does not seem like a good solution because endl abstracts the particular system-specific ways an end line might be specified, where as \n does not. This also seems like a poor solution because, should I need buffering in the future, I would then have to modify the whole code base.

Therefore, I ask, is there a way to disable the buffer-flushing aspect of endl?

EDIT

Further digging seems to indicate that both endl and \n respect the various ways an OS might choose to end it's lines. It also seems that the output stream detects if it's in a potentially interactive situation and buffers and flushes accordingly. Therefore: the problem may be solved by manually telling the output stream to perform aggressive buffering... if I can figure out how to do that.

解决方案

endl abstracts the particular system-specific ways an end line might be specified, where as \n does not".

std::endl is defined to output '\n' followed by a flush. The correct abstraction of the system-specific newline thingy is just '\n'.

To prevent flushes, one just doesn't use std::endl. In addition, the standard output may be line-buffered if it is or may be connected to an interactive device, in this case the newline character will flush the stream. If that's an issue, use an ofstream connected to a named file. I think on Unix-like systems line buffering only happens when the standard output is a terminal.

这篇关于告诉`endl`不要刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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