-3

I have googled and searched for a solution.

But nothing has worked for me so far.

If you know a function that will calculate white space and center text output for C++, I would appreciate it if you shared it.

sources:

C++ alignment when printing cout <<

http://www.worldbestlearningcenter.com/tips/text-alignment-in-Cplusplus.htm

https://www.experts-exchange.com/questions/21731990/Horizontally-center-align-text-in-C-console-application.html

Pang
  • 9,564
  • 146
  • 81
  • 122
Manual
  • 29
  • 1
  • 8

2 Answers2

1

I know this thread is old, but today I found myself with this problem and didn't really find any complete solution in the internet. So I made one myself, for any of the future people who are having the same issue.

The code I used is a simple function...

void CoutCentered(std::string text) {
// This function will only center the text if it is less than the length of the console!
// Otherwise it will just display it on the console without centering it.

HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); // Get the console handle.
PCONSOLE_SCREEN_BUFFER_INFO lpScreenInfo = new CONSOLE_SCREEN_BUFFER_INFO(); // Create a pointer to the Screen Info pointing to a temporal screen info.
GetConsoleScreenBufferInfo(hConsole, lpScreenInfo); // Saves the console screen info into the lpScreenInfo pointer.
COORD NewSBSize = lpScreenInfo->dwSize; // Gets the size of the screen
if (NewSBSize.X > text.size()) {
    int newpos = ((NewSBSize.X - text.size()) / 2); // Calculate the number of spaces to center the specific text.
    for (int i = 0; i < newpos; i++) std::cout << " "; // Prints the spaces
}
std::cout << text << std::endl; // Prints the text centered :]
}

If you're going to use this, remember to use #include <windows.h>. I've tested this on Visual Studio 2019 C++17 as a 32 bit dll, but it should work with a normal command line application.

  • Unfortunately, your code is going to fail miserably, if the line to be printed to the console is longer than the console window is wide: As `text.size()` is an unsigned number, the negative result of `NewSBSize.X - text.size()` will overflow to a huge positive number instead! So please add an `if` condition, that will print extra spaces only, if the line to be output actually fits into the console width. – Kai Petzke Apr 01 '21 at 03:33
  • Didn't think about that... You're right. Thanks for letting me know. – DownloadableFox Apr 01 '21 at 17:44
  • Ok, I've just edited the code. It should be fixed now. Thanks again for letting me know, I've been using the code a lot. – DownloadableFox Apr 01 '21 at 17:57
0

GetConsoleScreenBufferInfo then SetConsoleCursorPosition

Sahib Yar
  • 1,030
  • 11
  • 29
Minor Threat
  • 2,025
  • 1
  • 18
  • 32