In C++20 you’ll be able to use std::format to do this:
outputStream << std::format("|{:^10}|{:^10}|{:^9}|n",
"Table", "Column", "Header");
Output:
| Table | Column | Header |
In the meantime you can use the {fmt} library, std::format is based on. {fmt} also provides the print function that makes this even easier and more efficient (godbolt):
fmt::print("|{:^10}|{:^10}|{:^9}|n", "Table", "Column", "Header");
Disclaimer: I'm the author of {fmt} and C++20 std::format.
Here's a helper class that accomplish what you want:
#include
#include
#include
template
class center_helper {
std::basic_string
public:
center_helper(std::basic_string
template
friend std::basic_ostream& operator<<(std::basic_ostream& s, const center_helper& c);
};
template
center_helper
return center_helper
}
// redeclare for std::string directly so we can support anything that implicitly converts to std::string
center_helper
return center_helper
}
template
std::basic_ostream
std::streamsize w = s.width();
if (w > c.str_.length()) {
std::streamsize left = (w + c.str_.length()) / 2;
s.width(left);
s << c.str_;
s.width(w - left);
s << "";
} else {
s << c.str_;
}
return s;
}
It's used simply by calling centered("String"), like so:
int main(int argc, char *argv[]) {
std::cout << "|" << std::setw(10) << centered("Table")
<< "|" << std::setw(10) << centered("Column")
<< "|" << std::setw(9) << centered("Header") << "|"
<< std::endl;
}