The content of the file "person.txt" is
Sarah
22
Main Topics
Browse All Topics#include<iostream>
#include<fstream>
using namespace std;
class person
{
protected:
char name[40];
int age;
public:
void showdata(void)
{
cout<<"\n Name:"<<name;
cout<<"\n Age:"<<age;
}
};
void main(void)
{
person pers;
ifstream infile("person.txt");
infile.read((char *) &pers,sizeof(pers));
pers.showdata();
}
I compiled and run the above program. But junk values are displayed along with name and age. Why?
This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.
Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.
If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.
Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.
Access the answers to your technology questions today.
30-day free trial. Register in 60 seconds.
Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Try it out and discover for yourself.
30-day free trial. Register in 60 seconds.
Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.
Hi,
As you are reading from a text file, you cannot directly map the structure values to the data stored in your file. The Data has to be in the binary format which is in sync with your class members. i.e. your first name should always be of size 40 in your binary file followed by a 4 byte integer.
Dennis
If it is a must to read from text file and the content of the text file is as you have mentioned (name followed by newline followed by age), then write the main function as follows: -
void main()
{
person pers;
FILE * fp = fopen("c:\\person.txt", "r");
if(fp)
{
fscanf(fp, "%[^\n]", pers.name);
fscanf(fp, "%d", &(pers.age));
pers.showdata();
fclose(fp);
fp = NULL:
}
}
Note: In order for the above code to compile, you must make name and age as public. If, for some reason, you do not want to make them as public, then read name and age from the file into local variables, add some function to person class which takes name and age as arguments and from main function, call that function passing the local variables.
Business Accounts
Answer for Membership
by: avinash_sahayPosted on 2004-03-07 at 19:36:57ID: 10537966
You are reading from a text file. Can you tell me the content of the file?