Home > Article > Backend Development > How can I format data tables in C using the `` header?
Formatting a Data Table with C Headers
Formatting data tables in C can be done using methods provided in the
setfill(), setw(), and left/right
To create the desired table format, C offers three essential functions:
Example Code
Here's an example that will format a single row as shown in your desired format:
#include <iostream> #include <iomanip> using namespace std; int main() { const char separator = ' '; const int nameWidth = 6; const int numWidth = 8; cout << left << setw(nameWidth) << setfill(separator) << "Bob" << left << setw(nameWidth) << setfill(separator) << "Doe" << left << setw(numWidth) << setfill(separator) << 10.96 << left << setw(numWidth) << setfill(separator) << 7.61 << left << setw(numWidth) << setfill(separator) << 14.39 << left << setw(numWidth) << setfill(separator) << 2.11 << left << setw(numWidth) << setfill(separator) << 47.30 << left << setw(numWidth) << setfill(separator) << 14.21 << left << setw(numWidth) << setfill(separator) << 44.58 << left << setw(numWidth) << setfill(separator) << 5.00 << left << setw(numWidth) << setfill(separator) << 60.23; cout << endl; cin.get(); }
Using a Template Function
To simplify the code, consider using a template function:
template<typename T> void printElement(T t, const int& width) { cout << left << setw(width) << setfill(separator) << t; }
This function can be used to print each element with the specified width:
printElement("Bob", nameWidth); printElement("Doe", nameWidth); printElement(10.96, numWidth); printElement(7.61, numWidth); printElement(14.39, numWidth); printElement(2.11, numWidth); printElement(47.30, numWidth); printElement(14.21, numWidth); printElement(44.58, numWidth); printElement(5.00, numWidth); printElement(60.23, numWidth); cout << endl;
The above is the detailed content of How can I format data tables in C using the `` header?. For more information, please follow other related articles on the PHP Chinese website!