c++ - 使用 setw() c++ 格式化

标签 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 << " ";
    }

}

最佳答案

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

关于c++ - 使用 setw() c++ 格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42102202/

相关文章:

c++ - 根据签名区分专用结构

c++ - 如何确定已分配缓冲区的大小

c++ - 在非阻塞模式下在 TThread 中使用 TClientSocket 时不会触发 OnConnect 事件

c++ - 这是否提供自动内存管理以及内存控制? shared_ptr<unique_ptr<数据>>?

c++ - 为什么在 ADL 中重载优先于显式特化

c++ - 输出消失

c++ - 如何使用标志变量为设计用于在数组中搜索通过用户输入提供的字符串的程序产生输出?

c++ - 使部分代码中的变量不可用

Python (rospy) 到 C++ (roscpp) struct.unpack

c++ - 如何使用free删除链表