简体   繁体   English

std::cout output 的时机很奇怪

[英]The timing of std::cout output is strange

#include <iostream>
#include <thread>
#include <chrono>
using namespace std;

int main()
{
    std::cout << "1";
    std::this_thread::sleep_for( std::chrono::milliseconds(1000) );

    std::cout << "2";
    std::this_thread::sleep_for( std::chrono::milliseconds(1000) );

    std::cout << "3";
    std::this_thread::sleep_for( std::chrono::milliseconds(1000) );

    return 1;
}
  

I want std::cout to be printed every second.我希望每秒打印一次std::cout

But when I run this code, the result value 123 is printed at the same time.但是当我运行这段代码时,结果值123会同时打印出来。

Why?为什么?

And please tell me how to fix it.请告诉我如何解决它。

std::cout is buffered: std::cout被缓冲:

C++11 27.4.2 [narrow.stream.objects]/3: The object cout controls output to a stream buffer associated with the object stdout C++11 27.4.2 [narrow.stream.objects]/3: The object cout controls output to a stream buffer associated with the object stdout

so you need to explicitly flush this buffer to get what you want.所以你需要明确地刷新这个缓冲区来得到你想要的。 Here are some ways to do this:这里有一些方法可以做到这一点:

1. Use operator<< with std::flush 1. 将operator<<std::flush一起使用

std::cout << "1" << std::flush;

2. Use the free function std::flush(std::basic_ostream) 2. 使用免费的 function std::flush(std::basic_ostream)

std::cout << "1";
std::flush(std::cout);

3. Use the member function std::cout::flush() 3.使用成员function std::cout::flush()

std::cout << "1";
std::cout.flush();

4. Use operator<< with std::endl 4. 将operator<<std::endl一起使用

std::cout << "1" << std::endl;

This will of course also insert a line-break and is probably not what you want.这当然也会插入换行符,可能不是您想要的。

You may need to flush the standard stream after each cout otherwise they may wait till the end of the program to flush all at once.您可能需要在每个cout之后刷新标准 stream 否则他们可能会等到程序结束时一次性刷新所有内容。

Its due to buffering.这是由于缓冲。 After each cout , you are required to flush the buffer, by using any of the statements like std::flush(std::cout);在每个cout之后,您需要使用任何语句(如std::flush(std::cout);刷新缓冲区。 . .

This may help you.这可能会对您有所帮助。

#include <iostream>
#include <thread>
#include <chrono>
using namespace std;

int main(){
    std::cout << "1";
    //std::this_thread::sleep_for( std::chrono::milliseconds(1000) );
    std::flush(std::cout);

    std::cout << "2";
    //std::this_thread::sleep_for( std::chrono::milliseconds(1000) );
    std::flush(std::cout);

    std::cout << "3";
    //std::this_thread::sleep_for( std::chrono::milliseconds(1000) );
    std::flush(std::cout);

    return 0;
}

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

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