我在显示链接列表中的数据时遇到问题。我曾尝试在我的 for 循环中包含显示循环,并且只是为了检查它是否是指针和数据的问题,但我得到了相同的结果。
它显示第一个数据,但随后开始显示乱码。
#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();
}
对正确方向的任何建议和指示?
显然我正在关注某人的教程,但发生了这个错误。