[英]C++ ctime with ansi escapes
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
#define WIDTH 118
#define HEIGHT 60
void clearScreen(void) {
cout << "\033[2J\n";
}
void moveCursor(int row, int column) {
cout << "\033[" << row << ";" << column << "H";
}
void waitDelay(int sec) {
long startTime = time(NULL);
while(1) {
long currentTime = time(NULL);
if (currentTime - startTime > sec) {
break;
}
}
}
int main() {
char message[] = "* * * B R E A K * * *";
int messageLength = (sizeof(message) - 1) / sizeof(message[0]);
int startMessageCoord = (WIDTH - messageLength) / 2;
clearScreen();
for (int i = 0; i < messageLength; ++i) {
moveCursor((HEIGHT - 1) / 2, startMessageCoord + i);
cout << message[i];
waitDelay(1);
}
moveCursor(HEIGHT, 0);
return 0;
}
我的代码只有在“waitDelay(1)”行被注释并且知道为什么时才有效。 我的 waitDelay function 错了吗? 我希望消息会逐个字母地输出,但程序将等待 20 秒(所有字符延迟),然后将 output 完整消息。
您的 function waitDelay
运行良好。 错误在这里cout << message[i]
。 cout
被缓冲 stream。 你应该使用冲洗
使用cout
您需要使用endl
来立即获得 output。 所以代替cout << message[i];
使用cout << message[i] << endl;
编辑:显然, endl
具有在 stream 中添加换行符的副作用,这在大多数情况下可能是不可取的,尤其是在原始问题中。 所以是的, flush
对 go 来说是正确的,正如 OP 已经回答和接受的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.