Hi, I hope someone here can shed some light on a problem I'm having.
The simple program below reads a registry number and a name associated with it from the keyboard.
Upon exiting, all of the file contents are printed to the screen, this is working fine.
Accessing a specific name using the registry number doesn't work for some reason but for the life of me I can't figure it out.
Hope someone can take a look and help. Thanks.
Code:
#include <conio.h>
#include <iostream.h>
#include <fstream.h>
#include <cstdlib>
using namespace std;
class info {
private :
int regnum,status;
char name[50];
public :
int checkreg(int);
void write_name(int);
void read_name();
void print_all();
};
fstream A;
info names;
int info::checkreg(int n)
{
A.open("c:\\names.dat",ios::in|ios::binary);
A.clear();
if(A.good())
{
int flag=1;
while(A.read((char*)&names,sizeof(info))&&n!=regnum);
if(n==regnum&&status)
flag=0;
A.close();
return flag;
}
else cout<<"\nUnable to open file for checkreg";
}
void info::write_name(int n)
{
A.open("c:\\names.dat",ios::out|ios::binary|ios::app);
A.clear();
if(A.good())
{
regnum=n;
cout<<"\nEnter Name : ";
cin>>name;
status=1;
A.write((char*)&names,sizeof(info));
A.close();
cout<<"\nRegistry saved to file";
}
else cout<<"\nUnable to open file for write";
}
void info::read_name()
{
A.open("c:\\names.dat",ios::in|ios::binary);
A.clear();
if(A.good())
{
int num;
cout<<"\nEnter the registry number : ";
cin>>num;
while(A.read((char*)&names,sizeof(info))&&num!=regnum)
{
if(num==regnum&&status)
{
cout<<"Name : "<<name;
}
else cout<<"\nRegistry not found";
}
A.close();
}
else cout<<"\nUnable to open file to read";
}
void info::print_all()
{
A.open("c:\\names.dat",ios::in|ios::binary);
while(A.read((char*)&names,sizeof(info)))
{
cout<<"\n\n";
cout<<"\nRegnum = "<<regnum;
cout<<"\nName = "<<name;
}
}
int main(void)
{
int num;
char option;
do{
system("cls");
cout<<"\na - Write to file : ";
cout<<"\nb - Check a registry : ";
cout<<"\nc - exit and output all entries : ";
cout<<"\n\nEnter a b or c: ";
option=getche();
switch(option)
{
case 'a':
do{
cout<<"\nEnter registry number : ";
cin>>num;
if(names.checkreg(num))
{
names.write_name(num);
}
else cout<<"\nThis registry already exists";
cout<<"\nWould you like to enter another name? (y/n)";
}while(getche()!='n');
cout<<"\n";
getch();
break;
case 'b' : names.read_name();
cout<<"\n";
getch();
break;
case 'c' : break;
default : cout<<"\nThis option doesnt exist";
}
}while(option!='c');
names.print_all();
getch();
return 0;
}