簡體   English   中英

如何在C的單鏈表中調用字符串

[英]How to call string in singly linked list in C

這是我的結構

struct Student
{
    int numberofstudents;
    float mid,prj,final,hmw;
    int lettergrade;
    int studentnumber;
    char name[40];
    char lastname[40];
    int birthyear;
    float totalgrade;
    struct Student *next;
    
}* head;

我有一個像這樣的 function

void searchbylastname(char *lastname)
{
    struct Student * temp = head;
    while(temp!=NULL)
    {   
        if(temp->lastname == lastname){
        
            printf("Student Number: %d\n", temp->studentnumber);
            printf("Name: %s\n", temp->name);
            printf("Surname: %s\n", temp->lastname);
            printf("Birth Year: %d\n", temp->birthyear);
            printf("Total Grade: %0.2f\n", temp->totalgrade); 
            return;     
        }
        temp = temp->next;
    }
    printf("Student with student number %s is not found !!!\n", lastname);
}

我用開關盒在 main 中調用它

    head = NULL;
    int choice;
    char name[50];
    char lastname[50];
    int birthyear;
    int studentnumber;
    float totalgrade;
    float prj,hmw,mid,final;

    case 6:
                printf("Enter student lastname to search: "); 
                scanf("%s", &lastname);
                searchbylastname(lastname);
                break; 

但它不能按姓氏搜索,它會自動將我指向這里;

printf("Student with student number %s is not found !!!\n", lastname);

我不知道該怎么做,如果有人有意見,我將不勝感激。

==不比較 C 中的字符串,只比較這些字符串的引用(地址)。 如果它們沒有引用相同的 object,它們總是會有所不同。

要比較字符串,您需要使用strcmp function。

https://www.man7.org/linux/man-pages/man3/strncmp.3.html

您的代碼中有更多問題。 即使您使用strcmp ,它也會顯示未找到學生的消息。 如果您可能有更多的學生具有相同的 surmane (而期望您需要添加一個標志)

void searchbylastname(char *lastname)
{
    struct Student * temp = head;
    int studentsFound = 0;
    while(temp!=NULL)
    {   
        if(!strcmp(temp->lastname,lastname)){
            stutentsFound = 1;
            printf("Student Number: %d\n", temp->studentnumber);
            printf("Name: %s\n", temp->name);
            printf("Surname: %s\n", temp->lastname);
            printf("Birth Year: %d\n", temp->birthyear);
            printf("Total Grade: %0.2f\n", temp->totalgrade);  
        }
        temp = temp->next;
    }
    if(!studentsFound) 
       printf("Students having %s surname have not been found !!!\n", lastname);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM