I have wrote this code for my C++ class. now I have to move some of my data into a .dat file. I now how to ready and write but I having problem on how Im going to move my data into a file if I already create an array.
Can anyone help with this? I have add some instruction into the code.
/***
* Remove FruitFile structure and its data from this code.
* Create a data file (fruit.dat) and put all the hard coded data that is in a FruitFileData array
* into a fruit.dat file. You will not change any other logic of this code, just read the data from the
* file instead of an array.
#include <iostream>
#include <iomanip>
using namespace std;
struct FruitFile { // This data structure should be a record in a file
int Type;
int ID;
int Color;
int nTotalSeeds;
};
// Pineapple = 0
// Orange = 1
int main()
{
FruitFile FruitFileData[10] = { // This data should be in a file
{1,1,5,13},
{0,3,5},
{0,5,9},
{0,7,7},
{1,4,7,17},
{0,8,5},
{1,9,9,12},
{1,5,5,10},
{1,2,9,15},
{0,8,5}
};
CFruit *pFruit[10];
for (int i = 0; i < 10; i++) {
switch (FruitFileData[i].Type) {
case PINEAPPLE: // Create Pineapple Object
pFruit[i] = new CPineapple();
break;
case ORANGE: // Create Orange Object
pFruit[i] = new COrange();
break;
default:
break;
}
pFruit[i]->GetData(FruitFileData[i]); // call appropriate function
} // end for loop
cout << "Following are Pineapple values\n";
cout << "\nFruit Type" << "\tFruit ID" << "\tShell Color" << "\n";
for (int i = 0; i < 10; i++) {
if (pFruit[i]->GetFruitType() == PINEAPPLE)
pFruit[i]->ShowData();
}
cout << "\n\nFollowing are Orange values\n";
cout << "\nFruit Type" << "\tFruit ID" << "\tPeel Color" << "\tTotal Seeds" << "\n";
for (int i = 0; i < 10; i++) {
if (pFruit[i]->GetFruitType() == ORANGE)
pFruit[i]->ShowData();
}
for (int i = 0; i < 10; i++) {
if (pFruit[i])
delete pFruit[i]; // Delete appropriate object
}