C++ 如何居中文本输出

C++ How can I center text output

本文关键字:输出 文本 何居中 C++      更新时间:2023-10-16

我已经用谷歌搜索并搜索了一个解决方案。

但到目前为止,没有任何效果对我有用。

如果您知道一个可以计算C++的空白和中心文本输出的函数,如果您分享它,我将不胜感激。

来源:

打印<<时C++对齐

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

我知道这个线程很旧,但今天我发现自己遇到了这个问题,并没有真正在互联网上找到任何完整的解决方案。所以我自己做了一个,给任何未来遇到同样问题的人。

我使用的代码是一个简单的函数...

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 :]
}

如果要使用它,请记住使用#include <windows.h>.我已经在Visual Studio 2019 C++17上将其作为32位dll进行了测试,但它应该与普通的命令行应用程序一起使用。

GetConsoleScreenBufferInfo然后SetConsoleCursorPosition