使用setw()c ++格式化

时间:2017-02-07 23:52:25

标签: c++

我正在尝试创建一个有组织的图表,其中包含每个月每种食物的金额。我能够排成第一排,但之后开始出现问题。这就是我最终的结果:Current Output

这是我尝试使用setw()编写的代码,但是在推出第一个数组元素之后我似乎无法更改它。

void sales_report()
{
for (int i = 0; i < 7; i++)
{
    cout << setw(17) << months[i] << " ";
}

cout << endl << foods[0] << " ";
for (int i = 0; i < 6; i++)
{
    sumapple += apples[i];
    cout << setprecision(2) << fixed << setw(8) << money << apples[i] << " ";   
}
cout << setprecision(2) << fixed << setw(8) << money << sumapple << endl;
cout << foods[1] << " ";

for (int i = 0; i < 6; i++)
{
    sumoranges += oranges[i];
    cout << setprecision(2) << fixed << setw(7) << money << oranges[i] << " ";
}
cout << setprecision(2) << fixed << setw(7) << money << sumoranges << endl;
cout << foods[2] << " ";

for (int i = 0; i < 6; i++)
{
    sumpears += pears[i];
    cout << setprecision(2) << fixed << setw(10) << money << pears[i] << " ";
}
cout << setprecision(2) << fixed << setw(10) << money << sumpears << endl;
cout << foods[3] << " ";

for (int i = 0; i < 6; i++)
{
    sumtomatoes += tomatoes[i];
    cout << setprecision(2) << fixed << setw(7) << money << tomatoes[i] << " ";
}
cout << setprecision(2) << fixed << setw(7) << money << sumtomatoes << endl;
cout << foods[4] << " ";

for (int i = 0; i < 6; i++)
{
    sumcherries += cherries[i];
    cout << setprecision(2) << fixed << setw(6) << money << cherries[i] << " ";
}
cout << setprecision(2) << fixed << setw(6) << money << sumcherries << endl << totalmonth;
for (int i = 0; i < 6; i++)
{
    total = apples[i] + oranges[i] + pears[i] + tomatoes[i] + cherries[i];
    cout << setprecision(2) << fixed << setw(9) << money << total << " ";
}

}

1 个答案:

答案 0 :(得分:1)

您在每个for循环中使用了不同的std::setw()值。因此错位。使用相同的值。