1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Help Please! My program crashes for no reason

Discussion in 'C++' started by shkhanal, Aug 1, 2010.

  1. shkhanal

    shkhanal New Member

    Joined:
    Aug 1, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    Kathmandu
    Home Page:
    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");
    }
     
  2. Ancient Dragon

    Ancient Dragon New Member

    Joined:
    Jul 23, 2010
    Messages:
    26
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    part time cashier at WalMart
    Location:
    near St Louis, IL, USA
    The read loop is wrong. Its not necessary to call eof()
    Code:
    while( fin.read((char*) &g10, sizeof(g10))
    {
       // blabla
    }
    
     
  3. puneet306

    puneet306 New Member

    Joined:
    Jul 10, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    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
     

Share This Page