我学到了在 cout 语句末尾使用 endl 来刷新缓冲区的艰难方法。我感到困惑的是为什么 endl 仅有时是必要的。通常我可以这样做
cout << "test";
,它会显示测试。但在一个长控制台程序的中间,我将有一个类似的 cout 语句,并且不会显示任何内容,并且代码不会继续。在末尾添加 endl 通过刷新缓冲区并显示文本来修复问题。但是,是什么导致缓冲区在某些情况下自动刷新而在其他情况下手动刷新呢?我无法提供任何示例代码,因为我不知道如何重现该问题,但我假设你们大多数人都已经看到了这一点。
I learned the hard way about using endl at the end of a cout statement to flush the buffer. What I'm confused about is why endl is only necessary sometimes. Usually I can just do
cout << "test";
And it will display test. But in the middle of a long console program I'll have a similar cout statement and nothing will display and the code won't move on. Adding endl to the end fixes the problem by flushing the buffer and displaying the text. But what causes the buffer to be automatically flushed in the some cases and manually flushed in others? I can't provide any sample code because I don't know how to reproduce the problem, but I'm assuming most of you have seen this.
发布评论
评论(2)
当缓冲区达到一定长度或程序正常终止时,缓冲区将被刷新。
When the buffer reaches a certain length or the program terminates normally, the buffer is flushed.
缓冲区自动刷新的时间和原因取决于您正在使用的特定平台的实现者。您不应该对缓冲区何时被刷新做出任何假设或猜测。
当你想显示文本时,只需添加std::endl即可。 ;)
When and why the buffer is flushed automatically is up to the implementers of the particular platform you're working on. You shouldn't make any assumptions or guesses about when the buffer will be flushed.
When you want to display text, just add the std::endl. ;)