Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center text in fixed-width field with stream manipulators in C++

Tags:

I am refactoring some legacy code which is using printf with longs strings (without any actual formatting) to print out plain text table headers which looks notionally like this:

|  Table   |  Column  | Header  | 

which are currently being produced like this:

printf("|  Table   |  Column  | Header  |"); 

I would like to produce the above with code to the effect of1:

outputStream << "|" << std::setw(10) << std::center << "Table"              << "|" << std::setw(10) << std::center << "Column"              << "|" << std::setw(9) << std::center << "Header"              << "|" << std::endl; 

which does not compile because <iomanip> has the stream manipulators std::left, std::right and std::internal, but does not seem to have any std::center. Is there a clean way to do this already in standard C++ libraries, or will I have to manually compute the necessary spacing?


1Even though this is more verbose than the C code, it will be less verbose in the long run because of the number of printf statements and the amount of infixed duplication in their strings. It will also be more extensible and maintainable.

like image 683
Keith Pinson Avatar asked Feb 13 '13 19:02

Keith Pinson


1 Answers

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.

like image 193
vitaut Avatar answered Oct 02 '22 12:10

vitaut