Search code examples
c++fstreamturbo-c++

why is the file not being created by f stream or even if it is the output is just garbage values?


I had to design a basic hospital management system by using Turbo C++ . everything seems to be working fine including the add record function but when i choose to view the records that were entered (through a main menu that was created using the same program) the function just starts displaying an infinite loop of random characters. moreover i can't seem to find the file that was created in C:\TurboC++\Disk\TurboC3\BIN.

I think that perhaps the problem arises because the file was not created and there may be another file with the same name as of the class.

p.s. i know that i am using an ancient relic so you don't need to mention that and its my first semester so i am still not aware with all the technical stuff so would very much appreciate if you kept the language as simple as possible to help me and others like me.

class hospital {
  int bill,
  ref,
  age;
  char disease[30],
  name[20],
  doctor[20],
  address[50],
  sex;
  public : void getdata() {
    cout<<"ENTER THE NAME OF THE PATIENT"<<endl;
    gets(name);
    cout<<endl<<"ENTER THE ADDRESS OF THE PATIENT"<<endl;
    gets(address);
    cout<<endl<<"ENTER THE NAME OF THE DIESEASE(S) OF THE PATIENT"<<endl;
    gets(disease);
    cout<<endl<<"ENTER THE SEX OF THE PATIENT(f/m)"<<endl;
    cin>>sex;
    cout<<endl<<"ENTER THE NAME OF THE DOCTOR"<<endl;
    gets(doctor);
    cout<<endl<<"ENTER THE PRESCRIPTION/REFERENCE no."<<endl;
    cin>>ref;
    cout<<endl<<"ENTER THE AGE OF THE PATIENT"<<endl;
    cin>>age;
    cout<<endl<<"ENTER THE BILL OF THE PATIENT"<<endl;
    cin>>bill;
  }
  void display() {
    cout<<endl<<"THE DETAILS OF THE PATIENT ARE AS FOLLOWS:"<<endl;
    cout<<"AGE:"<<age<<"\tREFERENCE/PRESCRIPTION no.:"<<ref;
    cout<<"\tTHE NAME OF PATIENT:";
    puts(name);
    cout<<endl<<"\tTHE NAME OF THE DOCTOR:";
    puts(doctor);
    cout<<endl<<"\tTHE DIAGNOSED/TESTED FOR DISEASE(S) IS/ARE :"<<endl;
    puts(disease);
    cout<<endl<<"THE SEX OF THE PATIENT IS "<<sex<<endl;
    cout<<endl<<"THE BILL OF THE PATIENT IS "<<bill<<endl;
    cout<<endl<<"THE ADDRESS OF THE PATIENT IS: "<<endl;
    puts(address);
  }
  int retref() {
    return ref;
  }
}

;
void main() {
  clrscr();
  hospital h;
  cout<<endl<<"\n\n\t\t\tLOADING...\n\t\tPLEASE WAIT..\n";
  system("pause");
  clrscr();
  cout<<endl<<"\tWELCOME TO THE HOSPITAL MANAGEMENT SYSTEM"<<endl;
  displayrec();
  getch();
}

this is the function to view all the records that were saved

void displayrec()
{
  hospital h;
  ifstream fin;
  fin.open("hospitalrecords.dat", ios: :binary);
  while(!fin.eof()) {
    h.display();
    if(fin.eof()) break;
  }
}

Solution

  • You don't read anything from the file, so eof() will always be false, leading to an infinite loop.

    You need to actually read something in the loop, and initialize h with the data you read.