C ++如何使文本输出居中

时间:2017-08-09 05:10:11

标签: c++ text

我用谷歌搜索并寻找解决方案。

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

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

来源:

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

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

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

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

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 进行了测试,但它应该适用于普通的命令行应用程序。