我正在尝试制作一个代码,询问用户他们想要接受多少学生。在此之后,用户将输入学生的姓名。
我所做的代码是:
void acceptingStudents()
{
node *temp = NULL, *head = NULL, *run = NULL;
int studentSize;
char studentName;
cout << "Number of students to be accepted: ";
cin >> studentSize;
for (int x = 1; x <= memberSize; x++)
{
cout << "Student's name: ";
cin >> studentName;
temp = new node();
temp->name = studentName;
temp->next = NULL;
temp -> prev = NULL;
if (head == NULL)
{
head = temp;
}
else
{
run = head;
while (run->next != NULL)
{
run = run->next;
}
temp -> prev = run;
run->next = temp;
}
}
}
void main ()
{
node *run = NULL;
acceptingStudents();
while (run != NULL)
{
printf("%d\n", run->name);
run= run->next;
}
_getch();
}
我希望这个输出类似于
Number of students to be accepted: 3
Student's name: Allison
Student's name: Gerry
Student's name: Sam
但我的代码只输出:
Number of students to be accepted: 3
Student's name: Allison
Student's name: Student's name:
如何解决此问题并确保用户输入的每个学生姓名成为每个节点的数据?我正在尝试制作这样的节点:
另一方面,我能够使用它来使用数字:
void addingNodes()
{
node *temp = NULL, *head = NULL, *run = NULL;
int studentSize;
int studentNumber;
cout << "Number of students to be accepted: ";
cin >> studentSize;
for (int x = 1; x <= studentSize; x++)
{
cout << "Student's class number: ";
cin >> studentNumber;
temp = new node();
temp-> value = studentNumber;
temp->next = NULL;
temp -> prev = NULL;
if (head == NULL)
{
head = temp;
}
else
{
run = head;
while (run->next != NULL)
{
run = run->next;
}
temp -> prev = run;
run->next = temp;
}
}
}
输出:
Number of students to be accepted: 5
Student's class number: 27
Student's class number: 12
Student's class number: 4
Student's class number: 8
Student's class number: 30
我唯一的问题是将它变成字符串而不是int,因为我需要名字而不是类号。
答案 0 :(得分:0)
我观察的一个问题是studentname的数据类型是字符,Make it string,它会正常工作。另一个问题是这行“run!= NULL”。您没有更新值运行。通过引用传递fuctioon“acceptingStudents()”或使变量“run”全局。在你给定的代码中,你提到它是char
答案 1 :(得分:0)
您需要使用字符串或字符数组来存储名称。
char studentName[SIZE];
std::string studentName;
你不能只是将一个字符数组分配给另一个。
如果您使用string
数据类型,则可以使用assign
函数。
std::string str;
str.assign("Hello World");
cout<<str;
除此之外,实现链表的代码似乎有些混乱。如果要实现单链表,为什么有两个指针(next和prev)?为什么不使成员函数在node
类中添加节点而不是在函数中明确地执行它?