提问者:小点点

带有ansi转义的C++ctime


#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(所有字符的延迟),然后将输出完整的消息。


共2个答案

匿名用户

您的函数waitdelay工作良好。 错误出现在cout<<<; 消息[i]COUT是缓冲流。 您应该使用同花顺

匿名用户

对于cout,您需要使用endl立即输出。 所以不是cout<<<; 消息[i];使用cout<<<; 消息[i]<<<; endl;

编辑:显然,endl有一个副作用,就是在流中添加了一个新行字符,这在大多数情况下可能是不可取的,特别是在原始问题中。 因此,是的,flush是正确的选择,正如OP已经回答并接受的那样。

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(带有|ansi|转义|c++ctime)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?