Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align output to center of screen - C++?

I am working on a C++ console app. I want to execute and print all the stuff at the centre of app window screen (horizontally + vertically) as shown below.

 --------------------------------
|                               |
|                               |
|         User : xyz            |
|         Pass : ****           |
|                               |
|                               |
 --------------------------------

I want to run my whole program as pointed out above. Is there any way to do so? Any help or suggestion would be appreciated.

like image 768
ashu Avatar asked Jan 14 '23 04:01

ashu


1 Answers

How about this (LIVE EXAMPLE):

#include <iostream>
#include <string>
#include <vector>


void centerify_output(std::string str, int num_cols) {
    // Calculate left padding
    int padding_left = (num_cols / 2) - (str.size() / 2);

    // Put padding spaces
    for(int i = 0; i < padding_left; ++i) std::cout << ' ';

    // Print the message
    std::cout << str;
}


int main() {
    std::vector<std::string> lines = {
        "---------------------------------",
        "|                               |",
        "|                               |",
        "|         User : xyz            |",
        "|         Pass : ****           |",
        "|                               |",
        "|                               |",
        "---------------------------------",
    };

    int num_cols = 100;

    // VIRTUAL BORDER
    std::cout << std::endl;
    for(int i = 0; i < num_cols; ++i) std::cout << ' ';
    std::cout << '|' << std::endl;

    // OUTPUT
    for(int i = 0; i < lines.size(); ++i) {
        centerify_output(lines[i], num_cols);
        std::cout << std::endl;
    }

    // VIRTUAL BORDER
    std::cout << std::endl;
    for(int i = 0; i < num_cols; ++i) std::cout << ' ';
    std::cout << '|' << std::endl;
}

You get the idea. When centering the output vertically, you just put padding end lines at the top of the console.

like image 163
Mark Garcia Avatar answered Jan 21 '23 05:01

Mark Garcia