我的目标是将 input.dat 文件存储到结构数组中,并输出作为枚举的福特、雪佛兰、本田和丰田的总数。在为此工作了几个小时后,我遇到了障碍。当我在 Visual Studio 中调试代码时,我在输出中收到负数。我被困住了,真的可以用一个解释来解释我所缺少的东西。
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
#include <conio.h>
#include <fstream>
using namespace std;
enum CarType
{
Ford,
Chevy,
Honda,
Toyota
};
struct CarCustomer
{
string firstName;
string lastName;
double price;
CarType carType;
};
void calcCarStats(CarCustomer arrCustomers[], int count, int carCount[])
{
for(int index = 0; index < count; index++)
{
carCount[arrCustomers[index].carType]++;
}
}
void displayCarTypeCounts(int carCount[])
{
for(int index = Ford; index <= Toyota; index++)
{
cout //<< translateCarTypeToText((CarType)index) << " "
<< carCount[index] << endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int count = 0;
CarCustomer arrCustomers[100]; //Array of structs for the Struct CarCustomer
CarCustomer carCustomer;
int carCount[100];
int carTypeInt;
double carPriceSum[100];
double carPriceAvg[100];
ifstream fin;
CarType carType; //CarType enum
fin.open("input.dat");
if(!fin)
{
cout << "Error opening file, check the file name" << endl;
_getch();
return -1;
}
while (!fin.eof())
{
fin >> arrCustomers[count].firstName;
fin >> arrCustomers[count].lastName;
fin >> arrCustomers[count].price;
fin >> carTypeInt;
arrCustomers[count].carType = (CarType)carTypeInt; //carType entry is an enum
count++;
//debug
/*
cout << arrCustomers[count].firstName << endl;
cout << arrCustomers[count].lastName << endl;
cout << arrCustomers[count].price << endl;
cout << arrCustomers[count].carType << endl;
cout << "------------------------" << endl;
count++;
*/
}
fin.close();
//displayCarTypeCounts(carCount);
calcCarStats(arrCustomers, count, carCount);
displayCarTypeCounts(carCount);
_getch();
return 0;
}
//<------Contents of Input.dat------------------>
Joe Smith 5999.99 0
Mary Doe 23999.99 1
Joe Green 1999.99 1
Jim Smith 4999.99 2
Jane Green 3999.99 0
Mark Doe 9999.99 1
John Peters 7999.99 2
Jim Green 8999.99 3
Mindy Doe 3999.99 2
Janet Green 6999.99 1
Mork Doe 2999.99 3
Jane Smith 3999.99 3
John Roberts 15999.99 1
Mandy Doe 12999.99 0
Janet Smith 6999.99 0
Macy Doe 14999.99 1