简体   繁体   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;
}

My code works only if the "waitDelay(1)" line is commented and idk why.我的代码只有在“waitDelay(1)”行被注释并且知道为什么时才有效。 is my waitDelay function wrong?我的 waitDelay function 错了吗? 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.我希望消息会逐个字母地输出,但程序将等待 20 秒(所有字符延迟),然后将 output 完整消息。

Your function waitDelay works well.您的 function waitDelay运行良好。 The mistake is here cout << message[i] .错误在这里cout << message[i] cout is buffered stream. cout被缓冲 stream。 You should use flush你应该使用冲洗

With cout you need to use endl to have immediate output.使用cout您需要使用endl来立即获得 output。 So instead of cout << message[i];所以代替cout << message[i]; use cout << message[i] << endl;使用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.编辑:显然, endl具有在 stream 中添加换行符的副作用,这在大多数情况下可能是不可取的,尤其是在原始问题中。 So yes, the flush is the right thing to go with, as already answered and accepted by the OP.所以是的, flush对 go 来说是正确的,正如 OP 已经回答和接受的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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