How to show all elements of an array declared in a struct in C?

0

In this code:

#include <stdio.h>
#include <stdlib.h>

struct cadastro {
   char nome[50];
   int idade;
   char rua[50];
   int numero;

   };
int main()
{
struct cadastro c[4]; //Array[4] de estruturas
for(int i=0; i<4; i++) {
    gets(c[i].nome);
    scanf("%d", &c[i].idade);
    gets(c[i].rua);
    scanf("%d", &c[i].numero);
}
 system("pause");
 return 0;
}

How to give print on all elements of the struct, without doing it manually with a printf. For it will display four times.

    
asked by anonymous 18.05.2015 / 05:27

2 answers

0

To print all elements at once with a single simple statement, use 1 function!

void cadastro_print(struct cadastro *p) {
    printf("nome: %s\n", p->nome);
    printf("idade: %d\n", p->idade);
    printf("rua: %s\n", p->rua);
    printf("numero: %d\n", p->numero);
    printf("\n");
}

and in main() , call this function

    for (int i = 0; i < 4; i++) cadastro_print(c + i);
    
18.05.2015 / 10:34
0

Hello, I think it was not clear what you wanted to ask.

First, there is no more recommended method for outputting values in C than with printf.

To print the names, just follow the same logic as you used to read them:

for (i=0;i<4;i++){
    printf("%s\n",c[i].nome);
}
    
18.05.2015 / 07:32