This is my code .. accually with this code i can only save one student data .. i want to save more than one and display them all ....
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();
}