2

Is there a way to use windows API (windows.h) to center the text output in the console window?

Or a function from another library, or a general possibility?

Currently I inserted several control characters, but depending on the resolution and size of the window it doesn't fit.

printf ("\n\t\t\t\t   --Men\x81--\n\n\t\t\t     1: Neue Spielrunde\n\t\t\t     2: Charaktere laden\n\t\t\t     3: Spielrunde speichern\n\t\t\t     4: Programm beenden\n\n");
kiner_shah
  • 3,939
  • 7
  • 23
  • 37
  • You need to find width of the terminal window (cmd). See [this](https://stackoverflow.com/a/23370070/4688321). – kiner_shah Sep 10 '19 at 06:01

2 Answers2

3

Taking reference of this answer:

#include <windows.h>
#include <stdio.h>
#include <limits.h>
#include <string.h>

void print_spaces(int n) {
    for (int i = 0; i < n; i++) printf(" ");
}

int main(void) {
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    int columns, rows, cols_by_2;

    // Get console window attributes - no. of columns in this case
    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
    columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;

    cols_by_2 = columns / 2;

    // Put all options in an array
    char options[4][100] = {"1: Neue Spielrunde", "2: Charaktere laden", 
                            "3: Spielrunde speichern", "4: Programm beenden"};

    char menu_header[5] = "Men\x81";
    int len_header_by_2 = strlen(menu_header) / 2;

    print_spaces(cols_by_2 - len_header_by_2);
    printf("%s\n", menu_header);

    // Find max half-length of string
    int max_val = INT_MIN;
    for (int i = 0; i < 4; i++) {
        int len_str = strlen(options[i]) / 2;
        if (max_val < len_str)
            max_val = len_str;
    }

    // Compute spaces to add for max half-length string
    int no_of_spaces = cols_by_2 - max_val;

    // Print all options using computed spaces
    for (int i = 0; i < 4; i++) {
        print_spaces(no_of_spaces);
        printf("%s\n", options[i]);
    }
    return 0;
}

Here's the link where I tested the underlying logic (excluding computing window attributes): http://ideone.com/KnPrct

kiner_shah
  • 3,939
  • 7
  • 23
  • 37
0

You can actually take full control of the graphics on a win32 console if you wish. Effectively you end up calling AllocConsole, and then FillConsoleOutputAttribute to set the colour attributes of the text, and FillConsoleOutputCharacter to specify the characters to display. It does however mean you end up avoiding cout/cin/printf/scanf entirely, which may or may not be an issue

robthebloke
  • 9,331
  • 9
  • 12