1

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.

2 Answers2

1
#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;
}
jignatius
  • 6,304
  • 2
  • 15
  • 30
0

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';
Andreas DM
  • 10,685
  • 6
  • 35
  • 62
  • Is there no way to make each row all on the same setw()? In other words, am I not able to just define 1 setw() and have the elements of the table be left and right justified in it? – ChrisTov0803 Aug 11 '19 at 14:52