带有 ansi 转义的 C++ ctime
C++ ctime with ansi escapes
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
#define WIDTH 118
#define HEIGHT 60
void clearScreen(void) {
cout << "3[2J\n";
}
void moveCursor(int row, int column) {
cout << "3[" << 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 函数错了吗?
我希望消息逐个字母输出,但程序将等待 20 秒(所有字符延迟),然后输出完整消息。
使用cout
您需要使用endl
才能立即输出。所以不用 cout << message[i];
使用 cout << message[i] << endl;
编辑:
显然, endl
具有在流中添加换行符的副作用,这在大多数情况下可能是不可取的,尤其是在原始问题中。所以是的,flush
是正确的选择,正如 OP 已经回答和接受的那样。
您的函数 waitDelay
运行良好。错误就在这里cout << message[i]
。 cout
是缓冲流。你应该使用 flush
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
#define WIDTH 118
#define HEIGHT 60
void clearScreen(void) {
cout << "3[2J\n";
}
void moveCursor(int row, int column) {
cout << "3[" << 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 函数错了吗? 我希望消息逐个字母输出,但程序将等待 20 秒(所有字符延迟),然后输出完整消息。
使用cout
您需要使用endl
才能立即输出。所以不用 cout << message[i];
使用 cout << message[i] << endl;
编辑:
显然, endl
具有在流中添加换行符的副作用,这在大多数情况下可能是不可取的,尤其是在原始问题中。所以是的,flush
是正确的选择,正如 OP 已经回答和接受的那样。
您的函数 waitDelay
运行良好。错误就在这里cout << message[i]
。 cout
是缓冲流。你应该使用 flush