cout with this_thread::sleep_for?

cout with this_thread::sleep_for?

本文关键字:sleep for thread with this cout      更新时间:2023-10-16

我正在使用this_thread::sleep_for()进行测试,以创建一个与cout类似的对象,除了在打印字符串时,每个字符之间会有很小的延迟。但是,它不是在每个字符之间等待 0.1 秒,而是等待大约一秒钟,然后一次打印所有字符。这是我的代码:

#include <iostream>
#include <chrono>
#include <thread>
class OutputObject
{
    int speed;
public:
    template<typename T>
    void operator<<(T out)
    {
        std::cout << out;
    }
    void operator<<(const char *out)
    {
        int i = 0;
        while(out[i])
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(speed));
            std::cout << out[i];
            ++i;
        }
    }
    void operator=(int s)
    {
        speed = s;
    }
};
int main(int argc, char **argv)
{
    OutputObject out;
    out = 100;
    out << "Hello, World!n";
    std::cin.get();
    return 0;
}

知道我做错了什么吗?

编辑:CoryKramer指出,std::flush是实时行动所必需的。通过将std::cout << out[i];更改为std::cout << out[i] << std::flush;,我解决了我的问题!

流具有缓冲区,因此cout在刷新流之前不会打印文本,例如endl刷新流并添加'n'调用以cin自动刷新流中的缓冲数据。尝试使用这个:

while(out[i])
{
   std::this_thread::sleep_for(std::chrono::milliseconds(speed));
   std::cout << out[i];
   std::cout.flush();
   ++i;
}