List item causing error in program C

1

Good evening guys.

I'm having a problem with a simple code, for a college job where I can not figure out why, since Dev-C ++ does not report any errors. To prevent someone from my college find this topic by chance and copy my code, I will use an example of the teacher himself, with the addition of what is giving error in my:

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

#define TAM 3

typedef struct{
    int cod;
    char nome[50];
    char telefone[20];
} tipo_pessoa;

int main(){
    tipo_pessoa lista[TAM];
    int i=0;
    for(i=0; i<TAM; i++){
        printf("Insira o nome da pessoa %d:\n", i+1);
        gets(lista[i].nome);
        fflush(stdin);
        printf("Insira o telefone de pessoa %d (XX XXXXX XXXX):\n", i+1);
        gets(lista[i].telefone);
        fflush(stdin);
        lista[i].cod = i+1;
    }       
    system("cls");
    printf("Os cadastros foram preenchidos...\n\n");
    system("pause");
    for(i=0; i<TAM; i++){
        printf("%s - %s - %s\n", lista[i].cod, lista[i].nome, lista[i].telefone);
    }
}

My problem is with lista[i].cod , which when trying to "print" on the screen, the program finishes on time. If I take out lista[i].cod of printf , the code runs normally. If I ask the user to specify the number, it returns a strange character, but still, I need the code to be automatically generated by system and need to be displayed in printf .

What am I doing wrong?

I'm sorry if it's something stupid I can not see, but I've been pounding my head for 4 hours.

    
asked by anonymous 30.06.2018 / 01:52

2 answers

1

Use %d instead of %s to print numeric codes:

 printf("%d - %s - %s\n", lista[i].cod, lista[i].nome, lista[i].telefone);

That is, the first %s was meant to be %d .

Also, never use the gets function. Instead:

gets(lista[i].nome);

Use this:

fgets(lista[i].nome, 50, stdin);

Instead of this:

gets(lista[i].telefone);

Use this:

fgets(lista[i].telefone, 20, stdin);

Reasons not to use gets I explain in this answer and I also talk about it new else .

Also watch out for fflush(stdin) . See more about this in this answer and in this other too .

Finally, Dev-C ++ is a very old and long abandoned idea. Look for another IDE for more modern C, such as Code :: Blocks, NetBeans, Visual Studio, etc.

    
30.06.2018 / 02:04
1
printf("%d - %s - %s\n", lista[i].cod, lista[i].nome, lista[i].telefone);

lista[i].cod is an integer, so you have to put %d to indicate that an integer will be written and not a %s of "string".

    
30.06.2018 / 02:04