Reputation: 27
If I am making a data table to show the results of several functions, how can I use the setw(), left, and right keywords to create a table which is formatted like this:
Height 8
Width 2
Total Area 16
Total Perimeter 20
Notice how the overall "width" of the table is constant (about 20 spaces). But the elements on the left are left justified and the values on the right are right justified.
Upvotes: 1
Views: 2196
Reputation: 6474
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
struct Result
{
std::string Name;
int Value;
};
int main()
{
std::vector<Result> results = { {"Height", 8}, {"Width", 2}, {"Total Area", 16}, {"Total Perimeter", 20} };
for (auto result : results)
{
std::cout << std::setw(16) << std::left << result.Name;
std::cout << std::setw(4) << std::right << result.Value << std::endl;
}
return 0;
}
Upvotes: 1
Reputation: 10998
You could do something like this:
// "Total Perimiter" is the longest string
// and has length 15, we use that with setw
cout << setw(15) << left << "Height" << setw(20) << right << "8" << '\n';
cout << setw(15) << left << "Width" << setw(20) << right << "2" << '\n';
cout << setw(15) << left << "Total Area" << setw(20) << right << "16" << '\n';
cout << setw(15) << left << "Total Perimeter" << setw(20) << right << "20" << '\n';
Upvotes: 0