简体   繁体   中英

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;
}

My code works only if the "waitDelay(1)" line is commented and idk why. is my waitDelay function wrong? I expected the message to be outputed letter by letter but instead the program will wait for 20s (delay for all characters) and then will output the full message.

Your function waitDelay works well. The mistake is here cout << message[i] . cout is buffered stream. You should use flush

With cout you need to use endl to have immediate output. So instead of cout << message[i]; use cout << message[i] << endl;

EDIT: Apparently, endl has a side effect of adding a new-line character into the stream, which may not be desirable in the most cases, and particularly in the original question. So yes, the flush is the right thing to go with, as already answered and accepted by the OP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM