: I'm infiling a struct and for whatever reason I just can't figure out what I need to do to get this to work.
:
:
: int main(){
:
: char cdNum[11];
: char cdTitle[41];
: long qtyOnHand;
: double cost;
CDRec** Inventory = calloc(1024, sizeof(CDRec*)) //alloc space for 1024 pointers.
: int count=0;
:
: ifstream infile("cd.txt");
:
: if(!infile){
: cerr << "Error: File does not exist\n";
: exit(0);
: }
: char c;
: while(infile.get(cdNum, sizeof(cdNum))){
: if(infile.eof())
: break;
:
: infile>>ws;
: infile.get(cdTitle, sizeof(cdTitle));
: infile >> qtyOnHand >> cost;
: infile>>ws;
Inventory[count] = new CDRec(cdNum, cdTitle, qtyOnHand, cost);
: count++;
: }
: infile.close();
: for(int i =0; i < count; i++){
: cout << Inventory[i].cdNum << setw(13) << Inventory[i].cdTitle << setw(43) << Inventory[i].qtyOnHand << setw(5) << Inventory[i].cost <<endl;
/* Don't forget to release memory!!!!
for(i =0; i < count; i++){
delete Inventory[i];
}
free(Inventory);
: }
: return 0;
: }
:
:
: The problem seems to be the while loop. I'm not used to inputting a char string first. The input of the struct works fine. Any help would be greatly appreciated.
:
With your old line
Inventory = new CDRec(cdNum, cdTitle, qtyOnHand, cost);
you lose the previous CDRec, and create a memory leak.
The problem is that you want Inventory to be an array of CDRec's but you are using it as a pointer to one instance of CDRec.
I corrected that in the red lines in the above code.
Greets,
Eric Goldstein
www.gvh-maatwerk.nl