I am using a combination of structs and nodes using a heavily modified linked list program to read a data file and print results, I have also commented out what I am trying to do to help people better understand. The only issue is that it has a strange output and I would like some input as to what I could do to fix my current code.
Have you tried printing the values of a student_record after you read them? You can't really know they've been read unless you've seen them immediately after reading.
Well commenting out L90-94 doesn't help as that messes up the reading of subsequent lines.
You also want to consider having a function to read one record into a student_record. Then you don't need separate code to read the first record and the next 9. You also shouldn't assume that there are 10 records - shouldn't the code read all the records present?
@seeplus the reason why I commented out those lines is because I get a segmentation error and the program does not work at all. So I made them comments.
int main(void)
{
ifstream infile;
infile.open("/Users/adam/desktop/temp/student_records.txt");
string line;
student_record *student = new student_record; // Pointer to student_record type
if (!infile)
{
cout << "Unable to open the student data file." << endl;
return 1; // Error code for file open error
}
cout << "Student File opened." << endl;
// Read and ingnore the first line of the file.
// They are not data lines.
getline(infile, line);
/*
// Read in the data for the first student
infile >> student->firstname >> student->lastname >> student->birthdate.month
>> student->birthdate.day >> student->birthdate.year
>> student->ID >> student->year >> student->major;
for (int k = 0; k < 7; k++)
infile >> student->homework_grades[k];
for (int k = 0; k < 3; k++)
infile >> student->exam_grades[k];
*/
student_record *root=NULL, *new_node;
// making first node
root=student;
student->link=NULL;
// reading remaining 9 data and making node
for(int i=0;i<10;i++)
{
student_record *new_node = new student_record;
student_record *current_node=root;
while(current_node->link) // traversing till last so that we can add node there
{
current_node=current_node->link;
}
infile >> new_node->firstname >> new_node->lastname >> new_node->birthdate.month
>> new_node->birthdate.day >> new_node->birthdate.year // reading data
>> new_node->ID >> new_node->year >> new_node->major;
for (int k = 0; k < 7; k++)
infile >> student->homework_grades[k];
for (int k = 0; k < 3; k++)
infile >> student->exam_grades[k];
current_node->link=new_node; // adding node
new_node->link=NULL;
}
// Printing
student_record *current_node=root;
while(current_node)
{
print_data(*current_node);
current_node=current_node->link;
}
enter_data(root);
return 0;
}
I attempted to just edit the for loop to read all records I just get a segmentation fault now.