1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
|
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstring>
using namespace std;
const int strSize = 200;
const int arraySize = 200;
struct carData
{
char model[strSize];
char make[strSize];
char color[strSize];
double price;
int miles;
};
void loadCars(ifstream &infile, carData cars[], int strSize, int &numOfCars);
void showCars(carData cars[], int numOfCars);
int main()
{
carData cars[arraySize];
int numOfCars = 0;
char textFile[strSize];
cout << "textile name?" << endl;
cin.getline(textFile, strSize);
ifstream infile(textFile);
if (!infile)
{
cout << "could not open file " << textFile << '\n';
return 1;
}
loadCars(infile, cars, strSize, numOfCars);
showCars(cars, numOfCars);
}
void loadCars(ifstream &inFile, carData cars[], int strSize, int &numOfCars)
{
while (numOfCars < arraySize && inFile)
{
inFile.getline((cars[numOfCars].model), strSize, ',');
inFile.getline((cars[numOfCars].make), strSize, ',');
inFile.getline((cars[numOfCars].color), strSize, ',');
// read price, then skip until comma found
inFile >> cars[numOfCars].price;
inFile.ignore(100, ',');
// read miles
inFile >> cars[numOfCars].miles;
// if everything ok so far, add 1 to count
if (inFile)
numOfCars++;
// ignore everything until end of line
inFile.ignore(100, '\n');
}
}
void showCars(carData cars[], int numOfCars)
{
for (int i=0; i<numOfCars; ++i)
{
cout << setw(4) << i
<< setw(20) << cars[i].model
<< setw(20) << cars[i].make
<< setw(20) << cars[i].color
<< setw(10) << cars[i].price
<< setw(10) << cars[i].miles
<< '\n';
}
}
|