簡體   English   中英

C++ ctime with ansi 轉義

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM