Why the order is not preserved when printing something, first with cerr and then cout?

女生的网名这么多〃 提交于 2019-12-05 07:01:29

std::cerr and std::cout are different streams and they are not synchronized. So you really can't assume anything about how output to both gets shown. In this case, the output happens to be shown before the error.

You can rely on the order within either stream.

Additionally, std::cout is buffered and std::cerr is not, and that often causes this kind of problem, but because you are using std::endl (which flushes the stream) this doesn't really apply in your case.

The order of those two lines was not changed. However, whatever code produced the output you saw failed to preserve the order in which the output was sent to the two streams. It's possible that it just waited and then read both streams to produce the final output. It's hard to be sure without knowing what your environment looks like.

Chris Dodd

Well, std::endl flushes the stream to the underlying device, which mean that the output cannot legally be what you describe -- the first endl is sequenced before the output to cout, so the cerr stream must be flushed and the output appear on the terminal before the second line is executed.

Which means there are a number of possibilities

  • your computer is broken or compiler is buggy (unlikely)
  • you've defined endl to be something other than std::endl, and it doesn't flush (possible if you're trying to be obfuscated)
  • you've redirected stdout and/or stderr to different devices/files/pipes and are later combining them, and that later combination step is reordering things.
  • your code is actually something other than what you've posted above, and the difference, while seemingly unimportant, is actually crucial.

So if you want a real answer to this question, you need to post and MVCE demonstrating what you are actually doing.

Eclipse CDT is inserting itself into the cerr and cout streams during the creation of your process. It may echo the cerr stream to one of its windows and then write to the intended console. A tee of sorts.

Since it is polling these streams, it is not be possible to synchronize them. This could explain the behavior.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!