Formatting console output into columns

May 22, 2012 at 7:39pm
I have a function void ShowList() that(theoretically) prints out my data into a neat column, but upon running i get a messy bunch of code. How would i go about using even spacing to display variables? Here is what i want the code to look like:


CarName    Model    PartNo.    Price    Quantity    PartName
Blah       Fr34     1          2.34     17          BUFFER
BlahAgain  RTY34    2          4.67     4           ENGINE


I cant seem to get the even spacing, the numbers usually just end up everywhere and the output looks crazy. Try to take into account that i have never used iomanip before, which is why im having problems getting this to work. Here is my attempt:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void ShowList(std::list<Car> _Car)
{
    std::cout << "VehicleName"   << std::left << std::setw(TAB)
    << "MODEL" << std::setw(TAB)
    << "PartNo." << std::setw(TAB)
    <<"Price"<< std::setw(TAB)
    <<"quantity" << std::setw(TAB)
    <<"PartName\n";
    for(std::list<Car>::iterator iter = _Car.begin(); iter != _Car.end(); iter++)
     {
         std::cout << std::setw(TAB) << iter->make
         << std::setw(TAB)  << iter->model << std::setw(TAB)
         << iter->partNo << std::setw(TAB)
         << iter->price << std::setw(TAB)
         << iter->quantity << std::setw(TAB)
         << iter->partname << "\n";
     }
}


Thanks for helping!
May 22, 2012 at 8:56pm
Line 3 should have a setw() before "VehicleName", but that's not the root of the problem you described.

What is TAB set at?

Can you give us some of your output?

To make it easier to follow your code, I would suggest putting each output on the same line as its formatter. Like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    std::cout << "VehicleName"
        << std::left << std::setw(TAB) << "MODEL"
        << std::setw(TAB) << "PartNo." 
        << std::setw(TAB) <<"Price"
        << std::setw(TAB) <<"quantity"
        << std::setw(TAB) <<"PartName\n";
    for(std::list<Car>::iterator iter = _Car.begin(); iter != _Car.end(); iter++)
    {
        std::cout << std::setw(TAB) << iter->make
            << std::setw(TAB)  << iter->model
            << std::setw(TAB)  << iter->partNo
            << std::setw(TAB)  << iter->price
            << std::setw(TAB)  << iter->quantity
            << std::setw(TAB)  << iter->partname
            << "\n";
    }


This will make it easier to see that you missed the setw() before "VehicleName" as well as the fact that you might want std::left before you insert anything into cout.
May 23, 2012 at 12:41am
Thank you very much doug4! i was able to fix my program and get the output i wanted.
Topic archived. No new replies allowed.