[英]Cout in loop doesn't print char by char as defined
I've recently started learning C++ at university and decided to advance a bit at home.我最近开始在大学学习 C++,并决定在家里进步一点。 I had the idea of making a program that, given a piece of text, would print out such text character by character with a small delay in-between (as seen in this video SUPER.HOT chat ).我想制作一个程序,给定一段文本,它会一个字符一个字符地打印出这样的文本,中间有一个小的延迟(如这个视频SUPER.HOT chat 中所见)。
I tried to recreate it using a simple procedure:我尝试使用一个简单的程序重新创建它:
void typer(string text){
for (int i = 0; i < text.length(); i++){
cout << text[i];
usleep(100000);
}
But when usleep() is set under 103900, it'll start printing out two characters at a time.但是当 usleep() 设置为 103900 时,它将开始一次打印两个字符。 My intention is to print only 1 at a time but very quickly.我的目的是一次只打印 1 个,但速度非常快。
Any suggestions?有什么建议? :D :D
You need to flush the stream, otherwise it will be cached需要刷新流,否则会被缓存
cout.flush();
http://www.cplusplus.com/reference/ostream/basic_ostream/flush/ http://www.cplusplus.com/reference/ostream/basic_ostream/flush/
You need flush output你需要刷新输出
cout << text[i] << flush;
The usleep()
function returns 0
on success. usleep()
函数在成功时返回0
。 On error, -1
is returned, with errno set to indicate the cause of the error.出错时,返回-1
,设置 errno 以指示错误原因。
ERRORS EINTR
Interrupted by a signal; ERRORS EINTR
被信号中断; see signal(7).见信号(7)。
EINVAL
usec is not smaller than 1000000
. EINVAL
usec 不小于1000000
。 (On systems where that is considered an error.) (在被视为错误的系统上。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.