2

When my print function is called multiple times, the formatting of the list being printed gets changed.

I've tried researching ways to use the setw and other ostream modifiers, but cannot find the issue that is causing the list to be changed after the first iteration.

Here is the function I am using to print my arrays:

void printArray(Car array[], int n)
{
    cout << "Make" << setw(10) << "Model" << setw(13) << "Horsepower"
         << setw(8) << "Price\n\n";

    for (int i = 0; i < n; i++)
    {
        cout << setw(12) << left << array[i].make << setw(12) << left 
             << array[i].model << setw(6) << left <<  array[i].horsepower 
             << setw(9) << left <<  array[i].price;
        cout << endl;
    }
}

I was expecting the function to print something like this every iteration:

Make        Model   Horsepower Price

Lamborghini Diablo      550   290000
Honda       Civic       180   9000
Chevy       Silverado   300   30000

And here is the output that I get:

Make     Model   Horsepower Price

Lamborghini Diablo      550   290000
Honda       Civic       180   9000
Chevy       Silverado   300   30000


Sorted (ascending) by price:

MakeModel     Horsepower   Price

 Honda       Civic       180   9000
Chevy       Silverado   300   30000
Lamborghini Diablo      550   290000


Sorted (descending) by horsepower:

MakeModel     Horsepower   Price

 Lamborghini Diablo      550   290000
Chevy       Silverado   300   30000
Honda       Civic       180   9000
Stanky-kun
  • 71
  • 1
  • 1
  • 6

2 Answers2

0

You have to set the constant width using setw() method

Eg.
cout<<setw(20)<<"text";

0

As I mentioned in the comments, your first field was not set by setw, another thing to note is the use of endl instead of \n in the headers.

What you should be doing

void printArray(Car array[], int n)
{
    cout << left << setw(12) << "Make" << setw(10) << "Model" << setw(13) << "Horsepower"
         << setw(10) << "Price" << endl << endl;

    for (int i = 0; i < n; i++)
    {
        cout << setw(12) << left << array[i].make << setw(12) << left 
             << array[i].model << setw(6) << left <<  array[i].horsepower 
             << setw(9) << left <<  array[i].price;
        cout << endl;
    }
}
Arne
  • 1,293
  • 1
  • 7
  • 20