#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
class student
{
public:
string USN;
string Name;
string Branch;
int Semester;
string buffer;
void read_data();
void pack();
void write_to_file();
void unpack(int);
void search(string);
int hash(string);
};
int student::hash(string key)
{
int t;
t = (((key[7]-48) *100) + ((key[8]-48)*10) + (key[9]-48)) % 9;
if (t==0) return 9;
else return t;
}
void student::read_data()
{
cout<<"\nUsn:";
cin>>USN;
cout<<"\nName:";
cin>>Name;
cout<<"\nBranch:";
cin>>Branch;
cout<<"\nSemster:";
cin>>Semester;
}
void student::pack()
{
string sem,temp;
stringstream out;
out << Semester;
sem = out.str();
buffer.erase();
temp.erase();
temp+=USN+'|'+Name+'|'+Branch+'|'+sem;
for(;temp.size()<100;) temp+='$';
buffer=temp+'\n';
}
void student::write_to_file()
{
fstream file;
string temp;
int count, pos;
pos=hash(USN);
pos--;
pos=pos*304;
file.open("1.txt");
file.seekp(pos,ios::beg);
getline(file,temp);
file.close();
count=temp[0]-48;
file.open("1.txt");
if (count<0)
{
file.seekp(pos,ios::beg);
file.put('1');
pos=pos+1;
}
else if (count==1)
{
file.seekp(pos,ios::beg);
file.put('2');
pos=pos+102;
}
else if (count==2)
{
file.seekp(pos,ios::beg);
file.put('3');
pos=pos+203;
}
cout<<"\nInserting at:"<<pos;
file.seekp(pos,ios::beg);
file<<buffer;
file.close();
if (count==3) cout<<"\n\nCannot Insert....Overflow";
}
void student::unpack(int flag)
{
string sem;
int ch=1,i=0;
USN.erase();
if (flag==1) i++; //skip the count value
while (buffer[i]!='|')
USN+=buffer[i++];
Name.erase();
i++;
while (buffer[i]!='|')
Name+=buffer[i++];
Branch.erase();
i++;
while (buffer[i]!='|')
Branch+=buffer[i++];
sem.erase();
i++;
while (buffer[i]!='$')
sem+=buffer[i++];
istringstream out(sem);
out>>Semester;
}
void student::search(string key)
{
fstream file;
int flag=0, pos=0, count,i=1;
string temp;
pos=hash(key);
pos--;
pos=pos*304;
file.open("1.txt");
file.seekp(pos,ios::beg);
getline(file,temp);
count=temp[0]-48;
file.seekp(pos,ios::beg);
while (i<=count)
{
buffer.erase();
getline(file,buffer);
unpack(i++);
if (key==USN) flag=1;
}
if (!flag) cout<<"\n\nKey not found:";
else {
cout<<"\nThe Record details are-\n";
cout<<"\nUSN:"<<USN<<"\nName:"<<Name<<"\nBranch:"<<Branch<<"\nSemester:"<<Semester;
}
file.close();
}
int main()
{
int choice;
student s1;
string key;
while (1){
cout <<"\n\nMain Menu\n 1.Add \n\n 2.Search \n\n 3.Exit\n\nEnter the choice:";
cin>>choice;
switch (choice)
{
case 1: cout<<"Data\n";
s1.read_data();
s1.pack();
s1.write_to_file();
break;
case 2: cout <<"\n\nEnter the key";
cin>>key;
s1.search(key);
break;
case 3: return 0;
default: cout<<"\n\nWrong Choice";
}}
}
No comments:
Post a Comment