indjev99
indjev99

Reputation: 134

C++ The whole line is colored when it shouldn't be

I am using windows. I managed to simplify the problem to this.

#include<iostream>
#include<conio.h>
#include<windows.h>
using namespace std;
int main()
{
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),23);
    for (int i=0;i<400;++i)
    {
        cout<<i<<'\n';
    }
    cout.flush();
    getch();
    return 0;
}

It is supposed to color only the text and the whole lines but after the 300th line the whole line is colored and not just the text. There doesn't seem to be any difference between using '\n' and endl. Also it doesn't matter what the text is or if I change the color multiple times, just the number of lines. I also tried using printf and it doesn't make a difference as well.

This is a screenshot:

image

Any ideas why it is doing that and how I can fix it?

Upvotes: 0

Views: 293

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595827

The problem is that your loop is outputting more data than the console's screen buffer can hold. The initial buffer holds 300 lines. When your loop output exceeds the end of that initial buffer, the old content gets discarded, and apparently new content has now inherited the characteristics of the last output before discarding began. The color of unwritten buffer cells was initially black, but then became blue once the buffer started rolling.

You can use GetConsoleScreenBufferInfo() to retrieve the initial buffer size and then use SetConsoleScreenBufferSize() to increase the number of lines in the buffer. If you set the number of lines to 401+, you won't see blue filling whole lines anymore (assuming there was no content already being displayed onscreen when your app starts running).

HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

CONSOLE_SCREEN_BUFFER_INFO info = {0};
GetConsoleScreenBufferInfo(hConsole, &info);
info.dwSize.Y = 401;
SetConsoleScreenBufferSize(hConsole, info.dwSize);
SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | BACKGROUND_BLUE);

for (int i=0;i<400;++i)
{
    cout<<i<<'\n';
}
cout.flush();

image

Upvotes: 1

Related Questions