Home > front end >  how to write a reading function of a struct variable?
how to write a reading function of a struct variable?

Time:04-10

I have to write a function that reads from the keyboard a structure type variable and a function that displays a structure type variable. Subsequently, I have to use these functions to read and display a n number of elements of the structure. That's what I managed to write, but it does not look very correct and logical. I'd be very happy to help. Here's my code :

#include <stdio.h>


 struct data{
    int d, m, y;
}dt;


void readData(struct data element){
    printf("\nData format dd-mm-yyyy : ");
    scanf("%d %d %d", &element.d,&element.m,&element.y);
}

void read(struct data element,int n){
    for(int i = 0; i < n; i  ){
        readData(element);
    }
}
void display(struct data element){

     printf("\n %d.%d.%d\n",element.d,element.m,element.y);

}
void displayN(struct data element, int n){
    for(int i = 0; i < n; i  ){
        display(element);
    }
}
int main() {
struct data dd1;
    read(dd1,3);
    displayN(dd1,3);

    return 0;
}

CodePudding user response:

It looks like you want to use an array.

#include <stdio.h>


struct data{
    int d, m, y;
}dt;

/* use pointer to an element to modify the data */
void readData(struct data *element){
    printf("\nData format dd-mm-yyyy : ");
    scanf("%d %d %d", &element->d,&element->m,&element->y);
}

/* use an array to read data (just syntax sugar, this argument element is actually a pointer) */
void read(struct data element[],int n){
    for(int i = 0; i < n; i  ){
        readData(&element[i]);
    }
}

/* you don't need to use a pointer here because the value is just printed and not changed */
void display(struct data element){

     printf("\n %d.%d.%d\n",element.d,element.m,element.y);

}

/* use an array to print multiple data */
void displayN(struct data element[], int n){
    for(int i = 0; i < n; i  ){
        display(element[i]);
    }
}

/* define the number of elements and use that to avoid typo */
#define N 3

int main(void) {
    struct data dd1[N]; /* declare an array */
    read(dd1,N);
    displayN(dd1,N);

    return 0;
}
  •  Tags:  
  • c
  • Related