In C , efficiently formatting tabular data is made possible with the <
Consider the sample data below, where the goal is to align and format the data into columns and rows:
Bob Doe 10.96 7.61 14.39 2.11 47.30 14.21 44.58 5.00 60.23 Helen City 10.44 7.78 16.27 1.99 48.92 13.93 53.79 5.00 70.97 Joe Green 10.90 7.33 14.49 2.05 47.91 14.15 44.45 4.70 73.98
To align and format the data:
// Header Files #include <iostream> #include <iomanip> // Constants const char separator = ' '; const int nameWidth = 6; const int numWidth = 8; // Main Function int main() { // Example Usage cout << left << setw(nameWidth) << setfill(separator) << "Bob"; cout << left << setw(nameWidth) << setfill(separator) << "Doe"; cout << left << setw(numWidth) << setfill(separator) << 10.96; // ... (Additional code to continue formatting remaining data) // Maintain console cin.get(); return 0; }
Output:
Bob Doe 10.96 7.61 14.39 2.11 47.30 14.21 44.58 5.00 60.23
Alternatively, a template function can be defined to streamline the formatting process:
// Template Function for Efficient Formatting template<typename T> void printElement(T t, const int& width) { cout << left << setw(width) << setfill(separator) << t; } // Main Function int main() { printElement("Bob", nameWidth); printElement("Doe", nameWidth); printElement(10.96, numWidth); // ... (Additional code to continue formatting remaining data) // Maintain console cin.get(); return 0; }
With the template function, data formatting is simplified into a concise call:
printElement("Bob", nameWidth);
Utilizing these techniques in C , formatting data tables becomes effortless and customizable to your desired output.
The above is the detailed content of How can I efficiently format data tables in C using simplified syntax?. For more information, please follow other related articles on the PHP Chinese website!