c++ - Writing object array contents to and from file -


i trying write section of program read objects array text file , vice versa. can output objects file seemingly no issues, when try read data in text file empty array, places last object first 1 should , leaves others blank. going wrong?

here class code

//defining function items file void stock::writetofile(ofstream& fileout) {     fileout << stockcode << " ";     fileout << stockdesc << " ";     fileout << currentlevel << " ";     fileout << reorderlevel << " "; }  //defining function reading items in file void stock::readfromfile(ifstream& filein) {     while (filein >> stockcode >> stockdesc >> currentlevel >> reorderlevel)     {         filein >> stockcode;         filein >> stockdesc;         filein >> currentlevel;         filein >> reorderlevel;     } } 

and code in main

#include <iostream> #include <string> #include <fstream> #include "stock.h"  using namespace std;  int main() {     stock items[4];     int option = 0;     cout << "1.display full stock list." << endl;     cout << "please pick option: ";     cin >> option;     switch (option)     {     case 1:         cout << "stockcode" << '\t' << "stockdesc" << '\t' << '\t' << "currentlevel" << '\t' << "reorderlevel" << endl;         cout << "------------------------------------------------------------------------------" << endl;         ifstream filein;         filein.open("stock.txt");          (int = 0; < 4; i++)         {             items[i].readfromfile(filein);             cout << items[i].getcode() << '\t' << '\t';             cout << items[i].getdescription() << '\t' << '\t' << '\t';             cout << items[i].getcurrentlevel() << '\t' << '\t';             cout << items[i].getreorderlevel() << endl;         }     }     return 0; } 

this loop runs through entire file until can't read more, why last set of variables 1 visible. ones prior overwritten.

  while (filein >> stockcode >> stockdesc >> currentlevel >> reorderlevel)     {         filein >> stockcode;         filein >> stockdesc;         filein >> currentlevel;         filein >> reorderlevel;     } 

first time in loop, call

items[i].readfromfile(filein); 

cycles through entire file. remaining iterations in loop, try read file, it's @ eof.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -