#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)”行被注释并idk why的情况下才能工作。 我的waitDelay函数是不是错了? 我预计消息将一个字母一个字母地输出,但相反,程序将等待20s(所有字符的延迟),然后将输出完整的消息。
您的函数waitdelay
工作良好。 错误出现在cout<<<; 消息[i]
。 COUT
是缓冲流。 您应该使用同花顺
对于cout
,您需要使用endl
立即输出。 所以不是cout<<<; 消息[i];
使用cout<<<; 消息[i]<<<; endl;
编辑:显然,endl
有一个副作用,就是在流中添加了一个新行字符,这在大多数情况下可能是不可取的,特别是在原始问题中。 因此,是的,flush
是正确的选择,正如OP已经回答并接受的那样。