Click here to Skip to main content
15,892,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Everyone!

i am trying to make File handling program in C++,but i got the Error on Displaying the Records From the File.My Program take input from me Correctly but when the time is to View Program did not show me anything and Stop all Execution of the Program.

Please see the Below Program and tell me what is the Error in Displaying Part of The Program or Anywhere in the Program.
C++
#include <iostream>
#include <fstream>
using namespace std;

struct Student
{
private:
    string Name;
    int Age;
public:
    Student()
    {
        Name="";
        Age=0;
    }
    void GetData()
    {
        cout<<"Enter Name:";
        cin>>Name;
        cout<<"\nEnter Age:";
        cin>>Age;
    }
    void ShowData()
    {
        cout<<"Name:"<<Name;
        cout<<"\nAge:"<<Age;
    }
};
void Write_File()
{
    Student Obj;
    ofstream Input_Data;
    Input_Data.open("Student_Data.dat",ios::app|ios::binary);
    Obj.GetData();
    Input_Data.write(reinterpret_cast<char*> (&Obj),sizeof(Student));
    Input_Data.close();
}
void Display_Data()
{
    Student Obj;
    ifstream Output_Data;
    Output_Data.open("Student_Data.dat",ios::binary);
    while(Output_Data.read(reinterpret_cast<char*> (&Obj),sizeof(Student)))
    {
        Obj.ShowData();
    }
    Output_Data.close();
}
int main()
{
    Student Obj;
    char Choice;
    cout<<"Write Data Into The File."<<endl<<endl;
    do
    {
        Write_File();
        cout<<"\n\t\t\tDo You Want To Enter More Data Y/N :";
        cin>>Choice;
   }while(Choice=='y' || Choice=='Y');
    cout<<"\n\nOutput Of The Record:"<<endl;
    Display_Data();
    return 0;
}
Posted
Updated 27-Nov-14 6:07am
v2
Comments
Richard MacCutchan 27-Nov-14 13:09pm    
I suspect it is to do with reading the data directly into the object, rather than reading each property individually and recreating the object with a setter, or parameterised constructor.

1 solution

You have a scope problem.

You declare "Student Obj" in main() but never use it.

Replace ...

C#
void Write_File()
{
    Student Obj;


... with ...

C#
void Write_File(Student &Obj)
{


Do the same for Display_Data. Change you main function to something like this:

C++
int main()
{
    Student Obj;
    char Choice;

    cout << "Write Data Into The File." << endl << endl;
    do
    {
        Write_File(Obj);
        cout << "\n\t\t\tDo You Want To Enter More Data Y/N :";
        cin >> Choice;
    }
    while(Choice=='y' || Choice=='Y');
    cout << "\n\nOutput Of The Record:" << endl;
    Display_Data(Obj);
    return 0;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900