I’m encountering a problem with displaying data from the linked list. I have tried to both include the display loop inside my for loop and out just to check whether it was a problem with pointers and data but I’ve been getting the same result.
It displays the first data but then starts showing gibberish.
#include <stdio.h>
#include <conio.h>
#include <iostream>
#include <string>
void main(void) {
clrscr();
struct Student {
string Name;
double GPA;
Student *next;
};
Student *head;
head = NULL;
int ch, i;
string name;
double gpa;
cout << "How Many Records Do You Want To Enter?";
cin >> ch;
cout << endl;
for (i = 0; i < ch; i++) {
cout << (i + 1) << ". Name Of Student:";
cin >> name;
cout << "GPA Of Student:";
cin >> gpa;
cout << endl;
Student *newstudent;
Student *studentptr;
newstudent = new Student;
newstudent->Name = name;
newstudent->GPA = gpa;
newstudent->next = NULL;
if (!head)
head = newstudent;
else {
studentptr = head;
while (studentptr->next) {
studentptr = studentptr->next;
}
studentptr->next = new Student;
}
}
clrscr();
Student *display;
display = head;
while (display) {
cout << "Name:" << display->Name << endl;
cout << "GPA:" << display->GPA << endl;
display = display->next;
}
getch();
}
Any suggestions and pointers towards the right direction?
Apparently I was following someone’s tutorial but this error occurs.
studentptr->next = new Student;should bestudentptr->next = newstudent;