【问题标题】:delay output in c++ on linuxlinux上c++中的延迟输出
【发布时间】:2016-02-01 08:17:06
【问题描述】:

我希望将一些随机字符打印到控制台,然后由"\b" 删除。在此之后,我想放置我自己的变量,所以它看起来像“随机化”。问题是它发生得太快了。我想通过使用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";

    }
}

【问题讨论】:

    标签: c++ linux output delay


    【解决方案1】:

    问题是,std::coutis 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));
      

    【讨论】:

    • 可能是因为cout, not std::cout :)
    • @ikh 我只是尝试调整到 OP 的代码,因此假设前面有一个 using 指令。
    【解决方案2】:

    试试我来自 github 的小程序 slowtty。

    它允许您在 pty 中模拟旧 rs232c 行的行为,方法是延迟每个字符的输出,因为stty(1) 命令允许设置波特率。

    你用它来称呼它

    $ slowtty
    $ stty 1200
    $
    

    终端开始以缓慢的速度写入字符(如 1200 波特线)

    【讨论】:

      【解决方案3】:

      在许多系统上,输出是缓冲的。

      为确保您发送到 cout 的内容确实已从缓冲区中清除,您需要调用

      cout.flush();
      

      睡前

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-26
        • 1970-01-01
        相关资源
        最近更新 更多