mercredi 28 mars 2018

Compare Strings with if statenent in C

I'm a beginner in c programming and i'have come to a point (pretty ridiculous) that i'm stuck at an if statement between two strings.

In this program, i want the user to input a lesson of a student saved in a structure, then it should search for students with the same lesson and print them on screen. My problem is at if statement, for some reason (memory adress maybe?) when i type the same characters, it sees them for diffrent strings. The code just "skips" the if part. Although it works when i declare if(record[0].lesson!="maths") for instance.

i have tried lots of things such as strcmp, if (record[0].lesson==record[1].lesson), if(record[0].lesson=="maths")... and other.

I would highly appreciate it if you could help me. thank you very much.

# include <stdio.h>
# include <string.h>
typedef struct student{
    char name[10];
    char lesson[10];
}students;

int main()
{
    students record[10];
    char less;
    strcpy(record[0].name,"James");
    strcpy(record[0].lesson,"maths");
    strcpy(record[1].name,"John");
    strcpy(record[1].lesson,"maths");
    strcpy(record[2].name,"Harry");
    strcpy(record[2].lesson,"C/C++");
    printf("Give Lesson\n");
    scanf("%s",less);
    for(int i=0;i<3;i++){
    if(less==record[i].lesson)
    printf("%s\n",record[i].name);}


    return 0;
}

Aucun commentaire:

Enregistrer un commentaire