为什么cerr刷新cout的缓冲区 [英] why cerr flushes the buffer of cout

查看:230
本文介绍了为什么cerr刷新cout的缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
using std::cout;
using std::endl;
using std::cerr;
#include <cstdio>

int   main( )
{
    char pbuffer[BUFSIZ];
    setbuf(stdout, pbuffer);
    cout << "hello cout" ;
    sleep(5);
    cerr << "hello cerr";
    sleep(5);
    cout << "\nAll   done " << endl;
    sleep(5);
    return 0;
}

我编译并运行上面的程序后,输出是:

after I compile and run the program above, it's output is :

hello couthello cerr
All   done 

但我认为应该是:

hello cerrhello cout
All   done 

我想知道,为什么 cerr 缓冲区 cout

I want to know, why cerr flushes the buffer of cout ?

推荐答案

每当它感觉像。我有可能iostream的一些实现在输出到交互设备时改变缓冲策略。除非你有意在两个流的输出之间进行刷新,否则它们出现的顺序或多或少是未指定的;所有你可以指望的是单个< cerr 不会有 cout 。在你的情况下,实现是以某种方式同步 cout cerr 。 (你可能想看看会发生什么,如果你重定向他们的输出到不同的文件或者到同一个非交互式文件&C ++不区分交互式设备和其他人,但C,我希望大多数C ++实现遵循C )

First, a stream is allowed to flush whenever it feels like it. I possible that some implementations of iostream do change buffering policies when outputting to an interactive device. Unless you intentionally flush between outputs on the two streams, the order they appear is more or less unspecified; all you can count on is that a single << to cerr will not have characters from cout inserted into it. In your case, the implementation is synchronizing cout and cerr in some way. (You might want to see what happens if you redirect their output to different files. Or to the same non-interactive file—C++ makes no distinction between interactive devices and others, but C does, and I expect that most C++ implementations follow C in this respect.)

FWIW,关于订单的两个保证是:

FWIW, the two guarantees concerning order are:


  • cout cin 绑定,因此任何尝试在 cin 将清除 cout

  • cerr c> unitbuf 设置,因此它将在每个< 操作符结束时刷新。

  • cout is tied to cin, so any attempt to read on cin will flush cout, and
  • cerr has unitbuf set, so it will be flushed at the end of every << operator.

后者的想法是,我想,获得类似于C的行缓冲,C ++不直接支持—虽然如果你使用 std :: endl ,你将获得与行缓冲相同的效果。

The idea behind the latter is, I think, to obtain something similar to C's line buffering, which C++ doesn't support directly—although if you use std::endl, you get the same effect as line buffering.

这篇关于为什么cerr刷新cout的缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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