Search code examples
cfunctionstructcard

print id card information using two different function and should be called in main function


I want to print the id card using two different functions one for information from the user and the second function should display the information and should be called in the main function. please point out the mistake I am doing as it is not printing the proper value.

struct card
{
    char name[20];
    int clas;
    char section[20];
    int roll;
};

void info(struct card id)
{
    printf("\n Name: ");
    scanf(" %s", &id.name);
    printf("\nClass: ");
    scanf(" %d", &id.clas);
    printf("\nSection: ");
    scanf(" %s", &id.section);
    printf("\nRoll: ");
    scanf(" %d", &id.roll);
}

void displaydata(struct card id)
{
    printf("\nName: %s", id.name);
    printf("\nClass: %d", id.clas);
    printf("\nSection: %s", id.section);
    printf("\nRoll: %d", id.roll);
}

int main()
{
    struct card id2[4];
    int i;

    for (i = 0; i < 3; i++)
    {
        info(id2[i]);
    }

    for (i = 0; i < 3; i++)
    {
        printf("------");
        printf("student: %d", i + 1);

        displaydata(id2[i]);
    }

    return 0;
}

Solution

  • Here is your code modified to use a pointer for the two functions:

    #include <stdio.h>
    #include <stdlib.h>
    
    struct card
    {
        char name[20];
        int clas;
        char section[20];
        int roll;
    };
    
    void info(struct card *id)
    {
        printf("\n Name: ");
        scanf(" %s", &id->name);
        printf("\nClass: ");
        scanf(" %d", &id->clas);
        printf("\nSection: ");
        scanf(" %s", &id->section);
        printf("\nRoll: ");
        scanf(" %d", &id->roll);
    }
    
    void displaydata(struct card *id)
    {
        printf("\nName: %s", id->name);
        printf("\nClass: %d", id->clas);
        printf("\nSection: %s", id->section);
        printf("\nRoll: %d", id->roll);
    }
    
    int main()
    {
        struct card id2[4];
        int i;
    
        for (i = 0; i < (sizeof(id2) / sizeof(id2[0])); i++)
        {
            info(&id2[i]);
        }
    
        for (i = 0; i < (sizeof(id2) / sizeof(id2[0])); i++)
        {
            printf("------");
            printf("student: %d", i + 1);
    
            displaydata(&id2[i]);
        }
    
        return 0;
    }
    

    As you can see, I used sizeof to get the number of elements in the id2 array. This is much better than a magic number that the reader cannot easily find the signification.

    Also you should check if scanf is successful. For example:

    if (scanf(" %s", &id->name) != 1) {
        fprintf(stderr, "Name not correctly input\n");
        // more code to handle the error, as needed
    }