简体   繁体   English

用this_thread :: sleep_for进行侦听?

[英]cout with this_thread::sleep_for?

I'm testing using this_thread::sleep_for() to create an object that acts similarly to cout , except when printing strings it will have a small delay between each character. 我正在测试使用this_thread::sleep_for()创建一个行为类似于cout的对象,除了在打印字符串时,每个字符之间的延迟很小。 However, instead of waiting 0.1 seconds between each character, it waits about a second then prints it all at once. 但是,与其等待每个字符之间的0.1秒,不如等待大约一秒钟,然后一次打印所有字符。 Here's my code: 这是我的代码:

#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;
}

Any idea what I'm doing wrong? 知道我在做什么错吗?

Edit: CoryKramer pointed out that std::flush is required for it to act in real time. 编辑:CoryKramer指出,std :: flush是实时运行所必需的。 By changing std::cout << out[i]; 通过更改std::cout << out[i]; to std::cout << out[i] << std::flush; std::cout << out[i] << std::flush; , I solved my problem! ,我解决了我的问题!

Streams have buffer, so cout won't print text before you flush stream, for example endl flushes stream and adds '\\n' also call to cin automatically flushes buffered data in stream. 流具有缓冲区,因此cout不会在刷新流之前输出文本,例如endl刷新流并添加'\\n'也调用了cin自动刷新流中的缓冲数据。 Try to use this: 尝试使用此:

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

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

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