简体   繁体   English

c++ stream 缓冲和刷新

[英]c++ stream buffer and flush

#include <iostream>
#include <chrono>
#include <thread>

using namespace std::chrono;


int main() {
    std::cout << "hello";
    std::this_thread::sleep_for(2s);
    std::cout << "world"<<std::endl;
}

I m using visual studio 2019.我正在使用 Visual Studio 2019。
I expect above code to print helloworld after 2 seconds but hello is displayed before 2 seconds in the console(ie instantly when i run the program) and world is displayed after 2 seconds.我希望上面的代码在 2 秒后打印 helloworld,但 hello 会在 2 秒前在控制台中显示(即当我运行程序时立即显示),并且在 2 秒后显示 world。
I read about buffer recently and came to know that the text should be displayed in the console only after the buffer is full.我最近阅读了有关缓冲区的内容,并且知道只有在缓冲区已满后才能在控制台中显示文本。 We can force to flush the buffer by using \n , manupulators and cin.我们可以通过使用\nmanupulatorscin.

But why am I not seeing desired behavior in this particular example?但是为什么在这个特定的例子中我没有看到想要的行为呢?
Isn't cout using buffer? cout不使用缓冲区吗?
Is it flushed for every character?是不是每个角色都被刷新了?

There is no strict rule in the standard when a buffer should be flushed.何时刷新缓冲区,标准中没有严格的规定。

Like @Yksisarvinen mentioned in the comments, a flush isn't affected by the compiler but by the operating system.就像评论中提到的@Yksisarvinen 一样,刷新不受编译器的影响,而是受操作系统的影响。 Also \n doesn't always trigger a flush.另外\n并不总是触发刷新。 If the cout is going to a terminal, it is usually line buffered, thus you can force a flush via \n .如果cout要去一个终端,它通常是行缓冲的,因此你可以通过\n强制刷新。

More information can be found at: When does cout flush?更多信息请参见: cout 何时刷新? and Does new line character also flush the buffer? 换行符是否也刷新缓冲区?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM