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.