Hello!
i have the following data in a file

student_id student_name maths_score english_score physics_score

can i use a nested structure to read the file?

struct student
{	int id;
	char name[40];
};
struct score
{	int maths;
	int english;
	int physics;
};

if yes, how will i read the file into the structure?help me please

Recommended Answers

All 5 Replies

Hello!
i have the following data in a file

student_id student_name maths_score english_score physics_score

can i use a nested structure to read the file?

struct student
{	int id;
	char name[40];
};
struct score
{	int maths;
	int english;
	int physics;
};

if yes, how will i read the file into the structure?help me please

I'd probably add a data member of type score to the student struct, like this:

struct score
{	int maths;
	int english;
	int physics;
};
struct student
{	int id;
	char name[40];
        score studentScore;
};

All five pieces of information could then be stored in a single variable of type student. I guess I'd read from the file as follows, assuming you have an ifstream called ins.

student aStudent;
ins >> aStudent.id;
ins >> aStudent.name;
ins >> aStudent.studentScore.math;
ins >> aStudent.studentScore.english;
ins >> aStudent.studentScore.physics;

Now all of the information is in the variable aStudent.

if i have to sort the scores in maths, do i have to copy it to an array then sort it?

It might be best to read the file directly into the array of structs. Then when you sort the array by whatever field, all of the data for that student stays together. you can use the qsort() function, or if you want, store the structs in a list, and use the list.sort() function.

if i have to sort the scores in maths, do i have to copy it to an array then sort it?

Well if you have a whole bunch of students and you have an array of type student, I don't see why you couldn't just read it directly into the array.

student someStudents[100];
// miscellaneous code
ins >> someStudents[i].studentScore.math;

Same thing for the other attributes of the student struct. This reads directly into the array, which you can sort by math score later. No need to read it into aStudent and then copy from aStudent to the array. Just read it in directly.

i have tried to read 1 line from a file,and it works. but how to read a whole file if the number of lines in unknown?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.