Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Help Please! My program crashes for no reason (http://www.go4expert.com/forums/help-program-crashes-reason-t22892/)

shkhanal 1Aug2010 08:17

Help Please! My program crashes for no reason
 
Hi,

I intend to store objects in file and retrieve them. But the following program crashes when I compile and run on second time. for first time it runs. I guess there is some problem with append mode because if mode is selected output it runs without problem.

I'm using Dev-c++ to write and compile this program in Windows 7 OS.

Can you help me to identify the problem. I'm struck here when I need to write a program for payroll system of an organization (exam question).

Code:

#include<fstream>
#include<iostream>

using namespace std;

ofstream fout;
fstream fin;

class game{
      string name;
      int year;
  public:
      game(){name="Olympic"; year=2004;}
      game(string n, int y) {name=n; year=y;}
      string getName(){ return name;}
      int getYear(){ return year;}
      };

int main(){
  game g("World Cup",2010);
  game g10;
  fout.open("test.dat",ios::binary|ios::app);
  fout.write((char*) &g, sizeof(g));

  fout.close();
  fin.open("test.dat",ios::binary|ios::in);
  while(!fin.eof()){
      if(fin.eof())
      { cout<<"---End of File Reached ---"<<endl;
      }
            fin.read((char*) &g10, sizeof(g10));
            cout<<"\nName of Game: "<<  g10.getName();
            cout<<"\nYear of Game: "<<g10.getYear();
            cout<<"\n===================================="<<endl;
            }
  fin.close();
 
  system("Pause");
}


Ancient Dragon 1Aug2010 10:11

Re: Help Please! My program crashes for no reason
 
The read loop is wrong. Its not necessary to call eof()
Code:

while( fin.read((char*) &g10, sizeof(g10))
{
  // blabla
}


puneet306 17Aug2010 11:43

Re: Help Please! My program crashes for no reason
 
i think there is no prob with ur append mode but i think, when u are opening the file for writing but u are not using "out" mode. if this does not solve ur prob, then u can change the extension to ".txt" rather than using .dat mode there can be prob with ur one of "data types". also try to DEBUG the program using breakpoints


All times are GMT +5.5. The time now is 04:54.