cout with this_thread::sleep_for?
cout with this_thread::sleep_for?
我正在使用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;
}
相关文章:
- "error: no matching function for call to"构造函数错误
- 表示"accepting anything for this template argument" C++概念的通配符
- 如何在C++中从两个单独的for循环中添加两个数组
- 在Linux for Windows上编译C++代码时出错
- 调用专用模板时出错"no matching function for call to [...]"
- 为什么我的for循环不能正确获取argv
- 为什么我不能在 FOR LOOP 中使用 i/10,C++?
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- 在基于范围的for循环中使用结构化绑定声明
- 通过for循环使用用户输入填充列表
- boost::asio::steady_timer()与sleep()我应该使用哪一个
- 使用for循环检查数组中的重复项
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 正在使用for循环创建QScatterSerie
- Python中的for循环与C++有何不同
- std::memory_order for std::atomic:<T>:wait
- 在更改for循环的第三部分后,未使用for循环结果
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)