Thread: database problem

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    13

    database problem

    i have a small problem , when i exit the program ,open it again and load ( nothing loaded !!!!) i select display .. nothin is displayed.. i don't know if the problem is in the save() function or in the load() function ....

    ThanX


    Code:
    #include <iostream>
    #include <stdlib.h>
    #include <fstream>
    
    using namespace std;
    
    
    
       struct student
       {
             char fname[100];
             char lname[100];
             int id;
             float cgpa;
       };
    
       int add( student * , int &);
       void display( student * , int );
       void save(student * , int  );
       void load( student * , int );
    
    
    int main(int argc, char *argv[])
    {
       char x;
       student info [200 ];
       int i = 0 , num , max = 0;
    
       do
       {
            cout <<"============================\n";
            cout <<"            Menu            \n";
            cout <<"============================\n";
            cout <<endl;
            cout <<"={1}= Add a new student.\n";
            cout <<"={2}= Display all\n";
            cout <<"={3}= Save\n";
            cout <<"={4}= Load\n";
            cout <<"={5}= Exit\n";
            cout <<"============================\n";
    
    
            cout <<"Your Choice: ";
            cin >>x;
    
           switch ( x )
           {
                case '1' : add( info , i  );
                           break;
                case '2' : display( info , i);break;
                case '3' : save( info , i);break;
                case '4' : load( info , i );break;
                case '5' : ;break;
                default : cout <<"Invalid Choice\n";
           }
       }while ( x  !=  '5' );
    
    system("PAUSE");
    return 0;
    }
    
    //==================================================  ===
    
    //==================================================  ==========
    // Add a new student to the database
    int add(student * info , int & i )
    {
        
        if( i < 200 )
        {
            cout << "Enter student's first name: ";
            cin >>info[i].fname;
      
            cout << "Enter student's second name: ";
            cin >>info[i].lname;
      
            cout <<"Enter the student id: ";
            cin >> info[i].id;
      
            cout << "Enter the student CGPA: ";
            cin >> info[i].cgpa; 
    
          
            i++;
        }
        else
        {
            cout << "No more room in array!" << endl;
        }
    
        return 0;
    }
    //===============================[ display ]=======================
    void display( student * info , int max )
    {
    
          int i = 0;
    
          while ( i < max )
          {
               cout << "Name: "<< info [ i ].fname << " " << info [ i ].lname << endl;
               cout << "ID: " << info [ i ].id << endl;
               cout << "CGPA: "<< info [ i ].cgpa << endl;
               i ++;
          }
    
    }
    //========================[ save ]=============================
    void save( student * info , int i)
    {
          ofstream fout;
          fout.open("datab.txt",ios::out|ios::binary);
          fout.write(reinterpret_cast<char*>(&info[i]),sizeof(student));
          fout.close();
    
    }
    //=======================[load]=================================
    void load( student * info  , int i)
    {
          ifstream fin;
          fin.open("datab.txt",ios::in|ios::binary);
          fin.read(reinterpret_cast<char*>(&info[i]),sizeof(student));
          fin.close();
    }

  2. #2
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    the problem has to do with the way you are using i. Follow through with i for the first student info you add. In main() i is assigned zero. You then pass i to add() by reference. In add() i is incremented since zero is less than 200. i is now one. when add() terminates the value of i is still one back in main(). Then you send i by value to save() where you use it as the index of the student to save. However, there is no student at info[1], there is only a student at info[0] at this point. Therefore, you will either store junk in the file or nothing. Oooops. To store the last student added to info[] try using an index with value i - 1 like this:


    fout.write(reinterpret_cast<char*>(&info[i - 1]),sizeof(student));
    You're only born perfect.

  3. #3
    Registered User
    Join Date
    Mar 2005
    Posts
    13
    still i can't save or load data !!!! ....

  4. #4
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    I copied and pasted your program into DevC++. I made the change to the index in save() and load() and added some code in load() so I could see what was actually loaded back, and it worked fine for a single student. The problem came when I closed the program and restarted it. When I tried to read from file it didn't work because i was now 0 instead of 1, so when the correction was made as above, it caused a fence post error on the short side causing me to try to read into index -1 instead of 0.

    What to do? Well, I'd try passing only an array to load() and have load() read whatever is in the file into my array, overwriting what was already there, if anything. I'd keep a counter in load() to make sure I didn't read more than the 200 possible student values.

    void load( student * info)
    int i = 0;
    ifstream fin;
    fin.open("datab.txt",ios::in|ios::binary);
    while i < 200
    fin.read(reinterpret_cast<char*>(&info[i++]),sizeof(student));
    fin.close();


    Unforturnately I have to go now, so I can't try it myself. Good luck.
    You're only born perfect.

  5. #5
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    I've played with the program for some time now. I couldn't get it to work with your syntax so I changed a few things like making the variable names clearer, dropping the ios::binary, and using member by member read/write of structs. I also wrote the number of structs to be written to the file and to be read from the file to the file to make the syntax a little cleaner to me. I changed the save() function to save the entire info array each time the function was called by using the default ios::trunc rather than writing a single student to file each time save() called using ios::app. With those changes I got the program to work fine. It appears below.

    Then I tried using ios::binary rather than ios::trunc and that worked fine. Then I switched to full struct read/write rather than member by member read/write, and it flunked again. I tried changing the cast type to C style cast, but to no avail. However, I can't explain why this didn't work, as it should, from what little I know of that syntax.

    You really should test the files to be sure they are open before use and using the keyword const in a number of places is probably also worthwhile, but those are minor points for the learning process, and not the major points of the project, I'm sure.

    Code:
    #include <iostream>
    #include <stdlib.h>
    #include <fstream>
    using namespace std;
    
     
    
       struct student
       {
    		 char fname[100];
    		 char lname[100];
    		 int id;
    		 float cgpa;
       };
    
       int add( student * , int &);
       void displayStudents( student *, int);
       void save(student *, int);
       void load( student *, int &);
    
    
    int main(int argc, char *argv[])
    {
       char x;
       student info [200 ];
       int numOfStudents = 0;
    
       do
       {
    		cout <<"============================\n";
    		cout <<"			Menu			\n";
    		cout <<"============================\n";
    		cout <<endl;
    		cout <<"={1}= Add a new student.\n";
    		cout <<"={2}= Display all\n";
    		cout <<"={3}= Save\n";
    		cout <<"={4}= Load\n";
    		cout <<"={5}= Exit\n";
    		cout <<"============================\n";
    
    
    		cout <<"Your Choice: ";
    		cin >>x;
    
    	   switch ( x )
    	   {
    			case '1' : add( info , numOfStudents  );
    					   break;
    			case '2' : displayStudents( info , numOfStudents);break;
    			case '3' : save( info, numOfStudents);break;
    			case '4' : load( info, numOfStudents);break;
    			case '5' : ;break;
    			default : cout <<"Invalid Choice\n";
    	   }
       }while ( x  !=  '5' );
    
    system("PAUSE");
    return 0;
    }
    
    //==================================================	===
    
    //==================================================	==========
    // Add a new student to the database
    int add(student * info , int & numOfStudents )
    {
    
    	if( numOfStudents < 200 )
    	{
    		cout << "Enter student's first name: ";
    		cin >>info[numOfStudents].fname;
      
    		cout << "Enter student's second name: ";
    		cin >>info[numOfStudents].lname;
      
    		cout <<"Enter the student id: ";
    		cin >> info[numOfStudents].id;
      
    		cout << "Enter the student CGPA: ";
    		cin >> info[numOfStudents].cgpa; 
    
    	  
    		numOfStudents++;
    	}
    	else
    	{
    		cout << "No more room in array!" << endl;
    	}
    
    	return 0;
    }
    //===============================[ display ]=======================
    void displayStudents( student * studentArray , int numOfStudents )
    {
    
    	  int index = 0;
    
    	  while ( index < numOfStudents )
    	  {
    		   cout << "Name: "<< studentArray [ index ].fname << " " << studentArray [ index ].lname << endl;
    		   cout << "ID: " << studentArray [ index ].id << endl;
    		   cout << "CGPA: "<< studentArray [ index ].cgpa << endl;
    		   index++;
    	  }
    
    }
    //========================[ save ]=============================
    void save( student * info, int numOfStudents)
    {
    	  int index = 0;
    	  ofstream fout;
    	  fout.open("datab.txt");
    	  
    	  fout << numOfStudents << endl;
    	  
    	  for( ; index < numOfStudents; ++index)
    	  {
    		  fout << info [ index ].fname << " " << info [ index ].lname << ' ' <<info [ index ].id << ' ' << info [ index ].cgpa << endl;
    	   }	
    		
    		
    	  fout.close();
    
    }
    //=======================[load]=================================
    void load( student * info, int & numOfStudents)
    {
    	  ifstream fin;
    	  fin.open("datab.txt");
    	  
    	  fin >> numOfStudents;
    	  
    	  int index = 0;
    	  
    	  while(index < numOfStudents)
    	  {		  
    		  fin >> info [ index ].fname >> info [ index ].lname >> info [ index ].id >> info [ index ].cgpa;
    		  index++;
    		}
    		
    		
    	  fin.close();	
    }
    You're only born perfect.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 10
    Last Post: 05-18-2006, 11:23 PM
  2. Bin packing problem....
    By 81N4RY_DR460N in forum C++ Programming
    Replies: 0
    Last Post: 08-01-2005, 05:20 AM
  3. Developing database management software
    By jdm in forum C++ Programming
    Replies: 4
    Last Post: 06-15-2004, 04:06 PM
  4. Making a Simple Database System
    By Speedy5 in forum C++ Programming
    Replies: 1
    Last Post: 03-14-2003, 10:17 PM
  5. File Database & Data Structure :: C++
    By kuphryn in forum C++ Programming
    Replies: 0
    Last Post: 02-24-2002, 11:47 AM