You are here:

C++/Problems with file handling in C++

Advertisement


Question
Sir, I had written the following code in C++:

#include<iostream.h>
#include<fstream.h>
#include<conio.h>
class Student
{
int rollno;
char name[20];
char add[30];

public:
void enterdata(void);
void display(void);
};
void Student::enterdata(void)
{
cout<<"Enter Roll No. ";
cin>>rollno;
cout<<"Enter the name: ";
cin.getline(name, 20);
cout<<"Enter Address: ";
cin.getline(add, 30);
cout<<"\n";
}

void Student::display(void)
{
cout<<"ROLL NO. : "<<rollno<<"\t";
cout<<"NAME: "<<name<<"\t";
cout<<"ADDRESS"<<add<<"\t";
cout<<"\n";
}

int main()
{
clrscr();
Student s1[3];
fstream filin;
filin.open("stu.txt", ios::in|ios::out);
if(!filin)
{
cout<<"Cound not find file";
return 1;
}
cout<<"Enter records for 10 students\n";
for(int i=0;i<3;i++)
{
s1[i].enterdata();
filin.write((char*)& s1[i],sizeof(s1[i]));
}
for(i=0;i<3;i++)
{
filin.read((char*)& s1[i],sizeof(s1[i]));
s1[i].display();
}
filin.close();
return 0;
}
Now, watever values i enter some garbage gets stored in my text file which looks like:

  198 7$ L&9L   w 2#L  H>%z  @
103198

can u help me..........is thr some other way for executing programs wid file handling in TURBOC++ in DOS mode??????????  

Answer
Hello vineet, thank you for the question.

The reason you are writing garbage to the file is because you are casting the address of your Student to a char*. You could try something like making your Student have a WriteFile method like this:

void Student::WriteFile(ofstream &o)
{
o << rollno << ' ' << name << ' ' << add << '\n';
}

This will write the actual class values out, which you can read back in. This should have you pointing in the right direction.

I hope this information was helpful.

- Eddie

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 About.com. All rights reserved.