【问题标题】:How to slowdown an output character by character? (Mac OS)如何逐个字符地减慢输出速度? (苹果系统)
【发布时间】:2021-09-09 19:14:23
【问题描述】:

我的目标是一个一个地输出一串字符。但是当我运行它时,它会错开并最终只输出整个字符串,而字符之间没有延迟。我目前正在 Mac 操作系统上运行此代码。

#include <iostream>
#include <thread>
#include <chrono>

/**
    Asks user to input name.
    @param usrName Displays the the prompt asking for their name.
*/
void displaySequence(std::string usrName);

int main() {
    std::string prompt = "Name: ";
    std::string clientName;

    displaySequence(prompt);
    std::cin >> clientName;
    

    return 0;
}

void displaySequence(std::string usrName) {
    for (int i = 0; i < (int) usrName.length(); i++) {
        std::cout << usrName.at(i) << " ";
        std::this_thread::sleep_for(std::chrono::milliseconds(20));
    }
}

【问题讨论】:

  • 20 毫秒是一个非常短的延迟。每秒 50 个字符。这就是你想要的吗?

标签: c++ c++11 visual-c++ c++17


【解决方案1】:

std::cout 的输出通常是行缓冲的 - 也就是说,只有在遇到换行符(或缓冲区已满)时才会将其发送到终端。

您可以使用std::flush 修改此行为:

std::cout << usrName.at(i) << " " << std::flush;

任何缓冲的输出都将立即写入终端。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    相关资源
    最近更新 更多