gpt4 book ai didi

c++ - cout this_thread::sleep_for?

转载 作者:行者123 更新时间:2023-11-28 01:41:06 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com