Formatting Ouput

I'm writing a display function that takes an array of record objects which contain a first name, last name, classification, age, zip code, hometown, and GPA. I'm having a difficult time getting the output aligned with the column headers.

I tried using setw(), but the problem is that everything is of variable length, so I can't use a fixed setw() field that aligns the first character or number of a field under the first character of the specified column.
Any Ideas?

The first line is:
First Name Last Name Class Zip Age HomeTown GPA

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
void display(ostream& out, Record array[], int elems)
{

  for(int i = 0; i < elems; i++)
  {
    if(array[i].getFirst() == "I THINK THIS IS A DUPLICATE RECORD")
    {
      cout << array[i].getFirst() << endl;
    }
    else
    {
      cout << array[i].getFirst() << setw(15) << array[i].getLast() << 
      setw(15);
      
      cout << array[i].getClass() << setw(15) << array[i].getZip()  << 
      setw(15);
      
      cout << array[i].getAge()   << setw(15) << array[i].getHome() << 
      setw(15);
      
      cout << showpoint << setprecision(3)  << array[i].getGPA()   << endl;
    }

  }
}
Last edited on
having a difficult time getting the output aligned with the column headers.

I cannot be entirely sure here, since you don't show the code which generates those headings. However it appears that you are using the tab character '\t' in the headings? Thus:
The first line is:
 
First Name  \tLast Name      \tClass\tZip   \tAge\tHomeTown         \tGPA 


If I'm mistaken, please clarify. As it is, I can only advise against mixing setw() and the tab character for formatting. I would remove the tab character - if that is indeed what you are using - and use plain spaces.

In the actual code you have shown, it looks like you have things in the wrong order.
Here for example:
 
    cout << array[i].getFirst() << setw(15) << array[i].getLast() << setw(15);

I think what you are aiming to do is this:
 
    cout << setw(15) << array[i].getFirst() << setw(15) << array[i].getLast();


The point being here that setw() specifies the width of the next item to be output. It doesn't retrospectively act on items which have already been output.


Topic archived. No new replies allowed.