In C++ programming, we often want to print a string that is centered and padded with some characters so that the print out looks nice.
In this blog post, we will show how to center a string with padding characters in C++.
Centering String With Padding Characters
In the following example, we will show how to center a string with padding characters in C++ using the std::format function in C++20 and the std::string function in C++14.
#include<iostream> #include<string> #include<iomanip> // The format header might not be available in some compilers even if they support C++20. #if __cplusplus >= 202002L && __has_include(<format>) #include<format> #endif
std::string std_string_centered(std::string const& s, size_t width, char pad = ' ') { size_tconst l{s.length()}; // Throw an exception if width is too small. if (width < l) { throw std::runtime_error("Width is too small."); } #if __cplusplus >= 202002L && __has_include(<format>) // In C++20, center the string s and pad it with the pad character using runtime format. // We cannot use the std::format function here because it does not support runtime fmt string. // Use std::vformat instead. std::string const s_template{std::string("{:") + std::string(1, pad) + std::string("^{}}")}; std::string const s_centered{std::vformat(s_template, std::make_format_args(s, width))}; #else size_tconst left_pad{(width - l) / 2}; size_tconst right_pad{width - l - left_pad}; std::string const s_centered{std::string(left_pad, pad) + s + std::string(right_pad, pad)}; #endif return s_centered; }
The code can be compiled using G++ using C++14 or C++20. We could see that the string Hello, Underworld! was centered and padded to 40 characters using the character.
It’s possible that the format header is not available in some compilers even if they support C++20. To use a compiler that supports both C++20 and the format header, we can use the Docker container from the GCC Docker Hub. For example, we can use the GCC 13.2.0 Docker container gcc:13.2.0 pull the following command.