如何逐个字符地减慢输出速度? (Mac OS)
How to slowdown an output character by character? (Mac OS)
我的目标是一个一个地输出一串字符。但是当我 运行 它时,它会错开并最终输出整个字符串,字符之间没有延迟。我目前 运行 在 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;
任何缓冲的输出都将立即写入终端。
我的目标是一个一个地输出一串字符。但是当我 运行 它时,它会错开并最终输出整个字符串,字符之间没有延迟。我目前 运行 在 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;
任何缓冲的输出都将立即写入终端。