[英]delay output in c++ on linux
I want some random characters to be printed to console and then deleted by "\\b"
. 我想将一些随机字符打印到控制台,然后通过"\\b"
删除。 After this I want to put my own variable so it will be looking like "randomizing". 在此之后我想把我自己的变量放在一边,看起来像是“随机化”。 The problem is that it is happening too fast. 问题是它发生得太快了。 I wanted to delay the output by using usleep
or sleep
function but when I'm using it, nothing is printed into console. 我想通过使用usleep
或sleep
函数来延迟输出,但是当我使用它时,没有任何内容打印到控制台。
Short example: 简短的例子:
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
char chars[]={'a','b','c','g','h','u','p','e','y'};
for(int i=0; i<8; i++)
{
cout << chars[i];
usleep(200000);
cout << "\b";
}
}
Problem is, std::cout
is line-buffered . 问题是, std::cout
是行缓冲的 。 It stores all input in a buffer until a newline is encountered (or the program terminates). 它将所有输入存储在缓冲区中,直到遇到换行符(或程序终止)。 Use std::flush
to flush std::cout
explicitly: 使用std::flush
显式刷新std::cout
:
cout << chars[i] << flush;
Notes: 笔记:
since C++11, multithreading and time are standardized. 从C ++ 11开始,多线程和时间被标准化。 That brings the std::this_thread:sleep_for
function with it, which you should use for a portable >= C++11 program: 这带来了std::this_thread:sleep_for
函数,你应该将它用于便携式的> = C ++ 11程序:
std::this_thread::sleep_for(std::chrono::milliseconds(200));
On many systems output is buffered. 在许多系统上,输出都是缓冲的。
To ensure that what you sent out to cout
has really been flushed out of buffers you need to call 确保您发送给cout
内容确实已从您需要调用的缓冲区中清除
cout.flush();
before the sleep 睡觉前
Try my little program slowtty from github. 从github尝试我的小程序slowtty 。
It allows you to simulate in a pty the behaviour of an old rs232c line, by delaying the output per character as stty(1)
command allows to set the baudrate. 它允许您通过延迟每个字符的输出来在pty中模拟旧rs232c行的行为,因为stty(1)
命令允许设置波特率。
You call it with 你打电话给它
$ slowtty
$ stty 1200
$
and the terminal begins to write characters at a slow pace (like a 1200baud line) 终端开始慢速写字符(如1200波特线)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.