C++ 用户在链表(C+;+;)中输入(字符串)数据?
我试图制作一个代码,询问用户他们想要接受多少学生。在此之后,用户将输入学生的姓名 我制定的准则是:C++ 用户在链表(C+;+;)中输入(字符串)数据?,c++,string,linked-list,nodes,user-input,C++,String,Linked List,Nodes,User Input,我试图制作一个代码,询问用户他们想要接受多少学生。在此之后,用户将输入学生的姓名 我制定的准则是: void acceptingStudents() { node *temp = NULL, *head = NULL, *run = NULL; int studentSize; char studentName; cout << "Number of students to be accepted: "; cin >> stude
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: Student's name:
如何解决这个问题并确保用户输入的每个学生姓名都成为每个节点的数据?我试图使节点如下所示:
[Allison]->[Gerry]->[Sam]->NULL
另一方面,我能够使用以下方法处理数字:
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;
}
}
}
我唯一的问题是将其转换为字符串而不是int,因为我需要的是名称而不是类号。我观察到的一个问题是studentname的数据类型是character,将其转换为字符串,它就会正常工作。另一个问题是这行“run!=NULL”。您没有更新运行的值。通过引用传递函数“acceptingStudents()”中的run,或者使变量“run”为全局变量。在给定的代码中,您提到它char您需要使用字符串或字符数组来存储名称
char studentName[SIZE]代码>
std::string studentName代码>
也不能将一个字符数组分配给另一个字符数组
如果您使用的是字符串
数据类型,则可以使用分配
功能
std::string str;
str.assign("Hello World");
cout<<str;
std::string str;
str.assign(“你好世界”);
是否可以取消main()
?你的编译器有多老了?@EtienDemartel它应该是最新版本的studentName
是一个char
,意思是1个字符。您应该使用std::string
。如果你不允许,把名字存储在< C++ >代码> > ARAY.@混淆。
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
std::string str;
str.assign("Hello World");
cout<<str;