C++ 如何居中文本输出
C++ How can I center text output
我已经用谷歌搜索并搜索了一个解决方案。
但到目前为止,没有任何效果对我有用。
如果您知道一个可以计算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
相关文章:
- C++ 以相反的顺序输出文本文件
- 如何在不移动C 中的光标坐标的情况下输出文本以控制特定坐标
- 输出文本文件的位置
- 从输入复制到输出文本文件
- 输入和输出文本文件
- 您如何在输出文本的同时接受用户输入
- 如何从随机数中输出文本
- 使用读取系统调用C++输出文本
- 输出文本C++
- 将输出文本与 cout 对齐到右侧
- 如何在不使用cout/printf的情况下输出文本在cpp和c中
- 用户在输出文本时输入到控制台
- C++每x次输出文本
- outFile C++未写入输出文本
- C++:将输出文本格式化为.doc/.docx/.rtf(第2部分)
- 将输出文本格式化为.doc/.docx
- 从长期运行的控制台应用程序(C++)输入和输出文本
- 主函数不输出文本文件行
- 输出文本文件数据到字符数组
- 如何在c++中输出文本到打印机