Sainatarajan
Wise Old Owl
Question : I have to write a program to write object of class item to binary file then perform read,append,search and modify functions on the records. I have the written the following code.
Everything went well, i entered the new info , i viewed the new info, the i press 3 to modify, the program stops after i enter the new data using modify() on the previously entered data. Can someone Please help me. i have to submit this program tomorrow.
Code:
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
const char filename[] = "ITEM.TXT";
class item
{
int item_no;
char name[20];
long price;
public:
void new_item() // Get data from the user.
{
cout << "Enter The item Number : " << endl;
cin >> item_no;
cout << "Enter The item Name : " << endl;
cin >> name;
cout << "Enter The Price of the item : " << endl;
cin >> price;
}
void show_item() // Display the entered data.
{
cout << "Item Number : " << item_no << endl;
cout << "Item Name : " << name << endl;
cout << "Item Price : " << price << endl;
}
int getino() // Return the item number
{
return item_no;
}
void modify();
};
void item::modify() // To Modify a data.
{
cout << "Enter New Details : " << endl;
cout << "Enter New Item Number : " << endl;
cin >> item_no;
cout << "Enter New Item Name : " << endl;
cin >> name;
cout << "Enter New Item Price : " << endl;
cin >> price;
}
int main()
{
item i;
item itm;
char x = '0',ch='y';
int in;
while (ch=='y')
{
cout << "File Handling Menu :: \n"
"1) To Enter New Record : \n"
"2) To Append New Record : \n"
"3) To Modify Existing Records : \n"
"4) To View Records : \n"
"5) Exit\n" << endl;
cout << "Enter your choice : ";
cin >> x;
switch(x)
{
case'1':
{
ofstream fout(filename, ios::binary | ios::app);
itm.new_item();
fout.write((char*) &itm ,sizeof(itm));
fout.close();
}
break;
case'4':
{
ifstream fiot(filename, ios::binary);
cout << "Details Of Item : " << endl;
while (fiot.read((char*) &itm ,sizeof(itm)))
{
itm.show_item();
}
fiot.close();
}
break;
case'3':
{
fstream fil;
int in;
cout<<"Enter The Item Number To Modify : "<<endl;
cin>>in;
fil.open("ITEM.TXT",ios::in|ios::binary);
fil.read((char*)&itm, sizeof(itm));
while(!fil.eof())
{
if(in==itm.getino())
{
fil.seekg(0,ios::cur);
cout<<"Enter New Details.."<<endl;
itm.modify();
fil.seekp(fil.tellg() - sizeof(itm));
fil.write((char*)&itm, sizeof(itm));
}
}
fil.close();
}
break;
}
cout<<"Do you want to enter more press y : "<<endl;
cin>>ch;
}
return 0;
}