C++ 控制台文字居中函数:center(text)
C++ 控制台文字居中函数:center(text)
以下是一个用于居中文字的 C++ 控制台函数的示例:
#include <iostream>
#include <string>
void center(const std::string& text) {
int width = 80; // 控制台窗口宽度
int padding = (width - text.length()) / 2;
for (int i = 0; i < padding; i++) {
std::cout << ' '; // 将双引号改为单引号
}
std::cout << text << std::endl;
}
int main() {
std::string input;
std::cout << '请输入需要居中的文字:'; // 将双引号改为单引号
std::getline(std::cin, input);
center(input);
return 0;
}
使用该函数时,可以根据需要修改控制台窗口的宽度(变量width)。函数将根据窗口宽度计算出合适的左边填充空格数量,然后输出居中的文字。
原文地址: https://www.cveoy.top/t/topic/bI22 著作权归作者所有。请勿转载和采集!