0

该程序有效,我唯一的问题是我不知道如何排列输出。当使用 .txt 文件运行时,它会打印名称、框和 cookie 的名称,但未对齐。另外,我必须计算每个人的应付金额并显示出来,但我只能弄清楚如何计算总数。感谢帮助

#include <iomanip>
#include <string>
#include <fstream>
#include <iostream>
using namespace std;


int main()
{

ifstream inFile;
//Declare Variables

string firstName;
string cookieName;

int boxesSold;
int numCustomers = 0;
double amountDue;
int totalCustomers;
int totalBoxesSold = 0;
double totalAmount = 0;

cout << "Girl Scout Cookies" << endl;
cout << "Created By Aaron Roberts" << endl;

inFile.open("cookie.txt");
if(inFile)
{
cout << "Customer    Number      Cookie" << endl;
cout << "Name        Of Boxes    Name" << endl;

while(inFile >>firstName>>boxesSold>>cookieName)
{
    totalBoxesSold += boxesSold;
    totalAmount += boxesSold * 3.50;

    cout << setprecision(2) << fixed << showpoint;
    cout << setw(2) << firstName 
         << right << setw(7) << boxesSold
         << setw(20) << cookieName 
         << endl;
    numCustomers += 1;

}
cout << "\nNumber of Customers: "<< numCustomers << endl;
cout << "Total Boxes Sold: " << totalBoxesSold << endl;
cout << "Total Amount: $" << totalAmount << endl;
inFile.close();
}

else
{
cout << "Could not open file " << endl;
}

system("pause");
return 0;
}
4

1 回答 1

0

假设您在标题中为“客户名称”和“框数”列分配了 12 个字符,您可能希望为它们的数据分配 11 个字符,留下一个字符作为尾随空格。

为了清晰和可维护性,我建议您为这些创建常量:

int const name_column_width = 11;
int const boxes_column_width = 11;

然后你可以写:

    std::cout << std::setw(name_column_width) << std::left << "Customer" << ' '
        << std::setw(boxes_column_width) << std::left << "Number" << ' '
        << "Cookie"
        << std:: endl;

    std::cout << std::setw(name_column_width) << std::left << "Name" << ' '
        << std::setw(boxes_column_width) << std::left << "Of Boxes" << ' '
        << "Name"
        << std:: endl;

    while (inFile >> firstName >> boxesSold >> cookieName)
    {
        totalBoxesSold += boxesSold;
        totalAmount += boxesSold * 3.50;

        std::cout << std::setw(name_column_width) << std::left << firstName << ' '
            << std::setw(boxes_column_width) << std::right << boxesSold << ' '
            << cookieName 
            << std::endl;
        ++numCustomers;
    }

调整这些列的大小就变成了改变常数的简单问题。

于 2013-02-19T02:45:38.013 回答