如何正确格式化此打印功能?

时间:2019-07-10 05:37:10

标签: c++

当我的打印功能被多次调用时,正在打印的列表的格式会更改。

我尝试研究使用setw和其他ostream修饰符的方法,但是找不到导致列表在第一次迭代后发生更改的问题。

这是我用来打印数组的函数:

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;
    }
}

我期望函数在每次迭代时都打印出这样的内容:

Make        Model   Horsepower Price

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

这是我得到的输出:

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

2 个答案:

答案 0 :(得分:0)

您必须使用setw()方法设置恒定宽度

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

答案 1 :(得分:0)

正如我在评论中提到的,您的第一个字段不是setw设置的,另外要注意的是在标题中使用endl而不是\n

您应该做什么

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;
    }
}