linux 上的 C++ 延迟输出
delay output in c++ on linux
我想将一些随机字符打印到控制台,然后由 "\b"
删除。在此之后我想放置我自己的变量,所以它看起来像 "randomizing"。问题是它发生得太快了。我想通过使用 usleep
或 sleep
函数来延迟输出,但是当我使用它时,控制台中没有打印任何内容。
简短示例:
#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";
}
}
在许多系统上输出被缓冲。
为确保您发送到 cout
的内容确实已从缓冲区中清除,您需要调用
cout.flush();
睡前
问题是,std::cout
is line-buffered。它将所有输入存储在缓冲区中,直到遇到换行符(或程序终止)。使用 std::flush
显式刷新 std::cout
:
cout << chars[i] << flush;
备注:
从C++11开始,多线程和时间都标准化了。这带来了 std::this_thread:sleep_for
函数,您应该将其用于便携式 >= C++11 程序:
std::this_thread::sleep_for(std::chrono::milliseconds(200));
试试我的 slowtty 来自 github 的小程序。
它允许您在 pty 中模拟旧 rs232c 线路的行为,通过延迟每个字符的输出,因为 stty(1)
命令允许设置波特率。
你用
调用它
$ slowtty
$ stty 1200
$
终端开始以缓慢的速度写入字符(如 1200 波特线)
我想将一些随机字符打印到控制台,然后由 "\b"
删除。在此之后我想放置我自己的变量,所以它看起来像 "randomizing"。问题是它发生得太快了。我想通过使用 usleep
或 sleep
函数来延迟输出,但是当我使用它时,控制台中没有打印任何内容。
简短示例:
#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";
}
}
在许多系统上输出被缓冲。
为确保您发送到 cout
的内容确实已从缓冲区中清除,您需要调用
cout.flush();
睡前
问题是,std::cout
is line-buffered。它将所有输入存储在缓冲区中,直到遇到换行符(或程序终止)。使用 std::flush
显式刷新 std::cout
:
cout << chars[i] << flush;
备注:
从C++11开始,多线程和时间都标准化了。这带来了
std::this_thread:sleep_for
函数,您应该将其用于便携式 >= C++11 程序:std::this_thread::sleep_for(std::chrono::milliseconds(200));
试试我的 slowtty 来自 github 的小程序。
它允许您在 pty 中模拟旧 rs232c 线路的行为,通过延迟每个字符的输出,因为 stty(1)
命令允许设置波特率。
你用
调用它$ slowtty
$ stty 1200
$
终端开始以缓慢的速度写入字符(如 1200 波特线)