10'000 行后控制台中的 C++ 背景颜色错误

c++ wrong background colors in console after 10'000 lines

本文关键字:C++ 背景 错误 颜色 控制台      更新时间:2023-10-16

打印出比"屏幕缓冲大小"高度的线多(默认情况下为300,最多最多为9999(。第一白线的其余部分具有黄色背景。信息连续显示并突出显示重要部分,因此system("cls")不是首选选项。还有其他解决方案吗? Windows 7,MSVS社区2017,x86&x64

#include "Windows.h"
#include "stdio.h"
class Console {
    HANDLE h;
public:
    Console() { h = GetStdHandle(STD_OUTPUT_HANDLE); }
    void ChangeColor(WORD wColor) {
        if (h != INVALID_HANDLE_VALUE) SetConsoleTextAttribute(h, wColor);
    }
} console;
int main() {
    for (int i = 0;; i += 4) {
        console.ChangeColor(224);
        printf("highligted yellow, line = %5dn", i);
        console.ChangeColor(240);
        printf("plane whitennn");
        if (i %  1000 == 0) getchar();
    }
}

我认为控制台缓冲区被重复使用,并且您设置的颜色属性会与新线路混乱。您应该分配黑色并分别处理EOL。

for (int i = 0;; i += 4)
{
    console.ChangeColor(224);
    printf("highligted yellow, line = %d", i);
    console.ChangeColor(0);
    printf("n");
    console.ChangeColor(240);
    printf("plane white");
    console.ChangeColor(0);
    printf("nnn");
    if (0 == (i %  1000)) getchar();
}