Teoc
Teoc

Reputation: 103

How to make output text start on top left corner of console after newlines

After reading about why I should not use system("CLS"), I used cout << string(100, '\n') to clear the console screen. However, the new text would display at the last line of the console output. How can I fix that?

Using VC++ 2012.

Upvotes: 0

Views: 1264

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490108

Since you're apparently writing the code for Windows, you could use the Windows console functions, something like this:

#include <windows.h>

void ClrScrn(int attrib, char filler = ' ') {

    HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD pos = { 0, 0};
    DWORD written;
    CONSOLE_SCREEN_BUFFER_INFO screen_attr;
    unsigned size;

    GetConsoleScreenBufferInfo(screen, &screen_attr);

    size = screen_attr.dwSize.X * screen_attr.dwSize.Y;

    FillConsoleOutputCharacter(screen, filler, size, pos, &written);
    FillConsoleOutputAttribute(screen, attrib, size, pos, &written);
    SetConsoleCursorPosition(screen, pos);
}

This lets (requires) you specify the color it'll be cleared to in the parameter attrib, so usage would be something like this:

ClrScrn(FOREGROUND_BLUE | FOREGROUND_INTENSITY | BACKGROUND_BLUE);

If you want to clear the screen to something other than blanks, you can specify a character to fill with as well. For example to fill the screen with dark red smiley faces on a blue background:

ClrScrn(FOREGROUND_RED | BACKGROUND_BLUE, '\1');

Upvotes: 2

Related Questions