Thread: array of structure

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

    array of structure

    This is my code .. accually with this code i can only save one student data and display only one!! .. i want to add a new student data (without overwriting) and display them all (the new data and the saved ones as well)....


    ThanX ...


    Code:
    #include <iostream>
    #include <stdlib.h>
    #include <fstream>
    
    using namespace std;
    
    
    int add();
    void display();
    void save();
    void load();
    
    struct student{
           char fname[100];
           char lname[100];
           int id;
           float cgpa;
               };
               
    int main(int argc, char *argv[])
    {
      int x;
      
     
     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();break; 
      case 2 : display();break;
      case 3 : save();break;
      case 4 : load();break;
      case 5 : ;break;
      default : cout <<"Invalid Choice\n";
      }
      }while (x != 5);
      
      system("PAUSE");	
      return 0;
    }
    
    //==================================================  ===
    student info[200];
    int i,num;
    //==================================================  ==========
    // Add a new student to the database
    int add()
    {
        
      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; 
      
             
    }
    //===============================[ display ]=======================
    void display()
    {
            
              
            cout << "Name: "<<info[i].fname<<" "<<info[i].lname<<endl;
            cout << "ID: "<<info[i].id<<endl;
            cout << "CGPA: "<<info[i].cgpa<<endl;
    
            
    }
    //========================[ save ]=============================
    void save()
    {
            ofstream fout;
            fout.open("datab.txt",ios::out|ios::binary);
            fout.write(reinterpret_cast<char*>(&info[i]),sizeof(student));
            fout.close();
            
    }
    //=======================[load]=================================
    void load()
    {
            ifstream fin; 
            fin.open("datab.txt",ios::in|ios::binary);
            fin.read(reinterpret_cast<char*>(&info),sizeof(student));       
            fin.close();        
    }

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    You need to initialize i to 0 somewhere at the start of your program. Increment i after each addition of a new student. Your display and save functions must have some sort of loop in them so that they start at 0 and display (or write to a file) all the elements up to the current value of i. Your load function must reset i to 0 and then loop to read data from the file while incrementing i.

    [edit]Your add and load functions should also first check to make sure that i is not already equal to the number of elements in your array (200 in your case). If i is equal to 200, then you must stop.[/edit]
    Last edited by hk_mp5kpdw; 03-31-2005 at 06:36 AM.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Registered User
    Join Date
    Mar 2005
    Posts
    13
    Thanx man ...
    but i didn't get you clearly .... if I initialized i to 0, the loop will end at which value ?!

  4. #4
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Quote Originally Posted by ashb
    Thanx man ...
    but i didn't get you clearly .... if I initialized i to 0, the loop will end at which value ?!
    What loop?

    You initialize i to 0 at the start of the program. Each time you call your add function, you load the data into the array at the current i and then increment i by one. Your i variable thus serves as a counter indicating how many elements you have stored. When it comes time to call the display or save functions, you have a loop that goes from 0 up to (not including) i and outputs the values from the relevant array index. Your load function resets i to 0. Then it uses a loop to read in a single record's worth of data at a time and increments i by one for each record processed.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  5. #5
    Registered User
    Join Date
    Mar 2005
    Posts
    13
    sorry man but i'm still beginner ...

    i add a new student then I increme the i value (i++), how could i pass the new value of i from add() function to display and save functions ? ..

  6. #6
    Registered User
    Join Date
    Mar 2005
    Posts
    13
    I'm really stuck .. can any one help me !!!!

  7. #7
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    You don't need to pass around global variables, they can be used from any of your functions, although in order to initialize it in main you should declare it before main and not after. As a general rule, the use of globals should be avoided, but for this simple program they should be OK (otherwise you have to deal with passing values by pointer/reference). As an example, your add function should look like this:

    Code:
    int add()
    {
        // First make sure we have spare room in the array to store more data
        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; 
    
            // Now increment i to reflect the student we have just added
            ++i;
        }
        else
        {
            cout << "No more room in array!" << endl;
        }
    
        return 0;
    }
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  8. #8
    Registered User
    Join Date
    Mar 2005
    Posts
    13
    is there is somthing wrong with this load() function ??? when i call it, the is an error accures ...

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

  9. #9
    Senior Member joshdick's Avatar
    Join Date
    Nov 2002
    Location
    Phildelphia, PA
    Posts
    1,146
    Why are you opening the text up as binary? Also, I've never seen read() used like that. I don't think that's the best way to do it. Also, your i variable goes out of scope at the end of the function, so it's not doing anything for you right now. And it's a bad idea to make info a global variable.

    In the future, if you post the errors you get, it'll be easier for people to help you.
    FAQ

    "The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.

    "If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.

  10. #10
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Yes, there are many issues with the code. Your opening and closing of the file should be done outside of the loop. Testing of eof as a conditional in a loop is generally considered a bad idea. You are also declaring a new integer i which has nothing at all to do with your global i and so you don't know how many elements you will end up reading outside of the function itself. You should also test to make sure the file was opened successfully before you start to read from it. You also need to make sure we still have space before reading data into an invalid array location.

    Code:
    void load()
    {        
        i = 0;  // This will init the global i
        ifstream fin("datab.txt",ios::in|ios::binary);
    
        // Check if file is open first before we try to start reading from it
        if( !fin.is_open() )
        {
            cout << "load error: - Can't open input file!" << endl;
            return;
        }
        
        // Check we have space to store data before we actually try to
        // read data into an invalid index
        while( i < 200 && fin.read(reinterpret_cast<char*>(&info[i]),sizeof(student)) )
            ++i;     
    
        // An explicit call to fin.close(); is not needed since the stream
        // destructor will close the file for us automatically
    }
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  11. #11
    Registered User
    Join Date
    Mar 2005
    Posts
    13
    I have done some modification in the program but 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

  12. #12
    Registered User
    Join Date
    Mar 2005
    Posts
    13
    I have done some modification in the program but 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();
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Structure or Array?
    By epi_jimenez in forum C Programming
    Replies: 7
    Last Post: 04-01-2009, 02:45 PM
  2. linear search for structure (record) array
    By jereland in forum C Programming
    Replies: 3
    Last Post: 04-21-2004, 07:31 AM
  3. Type and nontype parameters w/overloading
    By Mr_LJ in forum C++ Programming
    Replies: 3
    Last Post: 01-02-2004, 01:01 AM
  4. Merge sort please
    By vasanth in forum C Programming
    Replies: 2
    Last Post: 11-09-2003, 12:09 PM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM