我有一个 Student
节点的链表:
struct Student
{
char name[20];
char Class[20];
string reg;
float cgpa;
int marks;
Student *next;
}*head,*lastptr;
我想做的是通过姓名搜索 Student
。
这是我的 searchStudent()
函数,它不起作用。我不知道是什么问题。
Student searchStudent(){
cout << "1. Search By Name" << endl;
cout << "2. Lower Then CGPA" << endl;
cout << "3. Equal To CGPA" << endl;
cout << "4. Greater than CGPA " << endl;
cout << "5. By Program " << endl;
cout << "6. Exit" << endl;
cout << endl;
char choice;
cin >> choice;
if(choice == '1'){
cout << endl;
char *name;
cout << "You chose option #1." << endl;
cout<<"Please enter name you want to search: " <<endl;
cin>>name;
cout << endl << "Listing all student Students : " << endl;
cout << "-----------------------" << endl;
Student *current;
current = head;
if (current->next == NULL) //Reached end of the list
{
cout<<"\n name not found in the Linked List \n";
}
while(current != NULL)
{
cout<<name[20];
cout<<current->name;
if (strcmp(current->name, name) == 0) { //found the element
cout << current -> name << endl;
cout << current -> Class << endl;
cout << current -> reg << endl;
cout << current -> cgpa << endl;
cout << current -> marks << endl;
current = current -> next;
cout << endl;
} else { //search next element
return searchStudent(); //this will call your function again for the next element on the list
}
}
}
这是我的控制台应用程序的图像:
最佳答案
char *name;
cout << "You chose option #1." << endl;
cout<<"Please enter name you want to search: " <<endl;
cin>>name;
您正在尝试读取指针中的学生姓名,而不是内存位置。
这样做:
char name[20]; // size taken from struct definition
cout << "You chose option #1." << endl;
cout<<"Please enter name you want to search: " <<endl;
cin>>name;
注意:您应该使用 std::string
在处理字符串时代替 char 数组。
关于c++ - 在 C++ 的链表中搜索 NAME,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59404130/