C++在Linux上如何延迟输出?

4

我希望在控制台打印一些随机字符,然后通过"\b"删除它们。之后,我想放入自己的变量,使其看起来像“randomizing”。问题是它发生得太快了。我想通过使用usleepsleep函数延迟输出,但是当我这样做时,控制台没有任何输出。
以下是一个简短的示例:

#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";

    }
}
3个回答

4

问题是,std::cout是行缓冲的。它会将所有输入存储在缓冲区中,直到遇到换行符(或程序终止)。使用std::flush来显式刷新std::cout

cout << chars[i] << flush;

注释:
  • since C++11, multithreading and time are standardized. 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(std::chrono::milliseconds(200));
    

可能是因为使用了cout,而不是std::cout :) - ikh
1
@ikh 我刚试着调整了一下原帖的代码,因此假设有一个前置的 using 指令。 - cadaniluk

1

请从github尝试我的小程序slowtty

它允许您在pty中模拟旧的rs232c线路的行为,通过延迟每个字符的输出,就像stty(1)命令允许设置波特率一样。

您可以使用以下方式调用:

$ slowtty
$ stty 1200
$

终端开始以缓慢的速度写入字符(类似于1200波特率线路)


1

许多系统会对输出进行缓存。

为确保您发送到 cout 的内容已真正从缓冲区中刷新出来,您需要调用:

cout.flush();

在睡觉之前

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接