如何逐字符减慢输出? 苹果系统

问题描述

我的目标是将一串字符一一输出。但是当我运行它时,它会交错并最终只输出整个字符串,而没有任何字符之间的延迟。我目前正在 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));
    }
}

解决方法

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

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

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

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