c++ - cout this_thread::sleep_for?

标签 c++ multithreading cout

我正在使用 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;
}

关于c++ - cout this_thread::sleep_for?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47114761/

相关文章:

c++ - 我应该为这个艺术项目使用哪个 IDE?

c++ - 使用 C++ 进行跨平台 GUI 开发

c++ - 如何使用预处理器检查 Objective-C++ 项目中是否正在编译 cpp 文件?

c# - 将两种形式作为不同的线程运行(或至少 2 种形式运行 "parallel")

PHP/MySQL 并发 - 写依赖于读 - 临界区

java - Spring-Hibernate 中的每个线程都应该有一个 EntityManager 吗?

时间:2019-03-09 标签:c++iomaniptableformatting

C++调试返回0返回变量

c++ - 无法从 C++ 循环中获得所需的输出 (cout)

c++ - cout什么时候刷新?