Home > Article > Backend Development > How can I format a data table in C using the `` library?
Using
For easy data table formatting in C , the
setw()
setw() specifies the minimum width of the output. It pads the remaining space with whitespace by default.
setfill()
setfill() allows you to set the character used to fill any extra space. For tabular alignment, you can use a space character (' ').
left() or right()
left() and right() control the alignment of the output. left() aligns the output to the left, while right() aligns it to the right.
Example Code
To format your data table as desired, use the निम्नलिखित कोड:
#include <iostream> #include <iomanip> using namespace std; const char separator = ' '; const int nameWidth = 6; const int numWidth = 8; int main() { cout << left << setw(nameWidth) << setfill(separator) << "Bob"; cout << left << setw(nameWidth) << setfill(separator) << "Doe"; cout << left << setw(numWidth) << setfill(separator) << 10.96; cout << left << setw(numWidth) << setfill(separator) << 7.61; cout << left << setw(numWidth) << setfill(separator) << 14.39; cout << left << setw(numWidth) << setfill(separator) << 2.11; cout << left << setw(numWidth) << setfill(separator) << 47.30; cout << left << setw(numWidth) << setfill(separator) << 14.21; cout << left << setw(numWidth) << setfill(separator) << 44.58; cout << left << setw(numWidth) << setfill(separator) << 5.00; cout << left << setw(numWidth) << setfill(separator) << 60.23; cout << endl; return 0; }
Template Function for Simplified Printing
To further simplify the formatting process, you can create a template function:
template<typename T> void printElement(T t, const int& width) { cout << left << setw(width) << setfill(separator) << t; }
You can then use this function as follows:
printElement("Bob", nameWidth); printElement("Doe", nameWidth); printElement(10.96, numWidth); printElement(17.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;
This approach streamlines the formatting process, making it easier to maintain and extend.
The above is the detailed content of How can I format a data table in C using the `` library?. For more information, please follow other related articles on the PHP Chinese website!