c++ - 在 C++ 的链表中搜索 NAME

标签 c++ c++11 linked-list

我有一个 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
            }
        }
    }

这是我的控制台应用程序的图像:

image

最佳答案

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/

相关文章:

没有纯虚函数的 C++ 抽象类?

c++ - 使'clean.Stop需要: *** No rule to make target 'rm' ,

C++ std::move 指针

java - LinkedList 中的序列化如何工作?

algorithm - 如何在不使用任何额外内存的情况下从 unicode 字符链表中消除重复项

c++ - 圆括号 "(*)"中的单个星号在 C++ 中有什么作用?

c++ - 为 Visual Studio 2013 安装 QT 插件

c++ - 合法使用 initializer_list 来初始化具有派生类型的对象吗?

c++ - 将绝对地址转换为指针变量的现代 C++ 方法是什么?

list - 学习箱形图和指针图的资源