0

Here is my struct

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;

And I have a function like this

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);
}

I'm calling it in main with switch case

    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; 

but it cannot search by last name, it's automatically direct me here;

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

I don't know what to do, if anyone has an opinion, I would really appreciate it.

1 Answers1

0

== does not compare strings in C only the references (addresses) of those strings. If they do not reference the same object they always will be different.

To compare strings you need to use strcmp function.

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

You have more problems in your code. Even if you use strcmp it will display the message that the student has not been found. If you may have more students having the same surmane (which rather expected you need add a flag)

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);
}
0___________
  • 60,014
  • 4
  • 34
  • 74