程序工作我唯一的问题是我不知道如何排列输出。使用.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;
}
答案 0 :(得分: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;
}
然后调整这些列的大小就变成了一个改变常量的简单方法。