[英]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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.