Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/132.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 可以用这个线程::睡眠吗?_C++_Multithreading_Cout - Fatal编程技术网

C++ 可以用这个线程::睡眠吗?

C++ 可以用这个线程::睡眠吗?,c++,multithreading,cout,C++,Multithreading,Cout,我正在使用this_thread::sleep_for()来创建一个类似于cout的对象,但在打印字符串时,每个字符之间会有一个小的延迟。但是,它不是在每个字符之间等待0.1秒,而是等待大约一秒钟,然后一次打印所有字符。这是我的密码: #include <iostream> #include <chrono> #include <thread> class OutputObject { int speed; public: template&

我正在使用
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;
}
#包括
#包括
#包括
类OutputObject
{
整数速度;
公众:
模板

void操作符流具有缓冲区,因此
cout
在刷新流之前不会打印文本,例如
endl
刷新流并添加
'\n'
也调用
cin
自动刷新流中的缓冲数据。请尝试使用以下方法:

while(out[i])
{
   std::this_thread::sleep_for(std::chrono::milliseconds(speed));
   std::cout << out[i];
   std::cout.flush();
   ++i;
}
while(out[i])
{
std::this_线程::sleep_for(std::chrono::毫秒(速度));

std::cout您可能只需要在
循环中执行
,同时记住
std::cout
的输出是缓冲的。