Problem in struct

Asked

Viewed 31 times

-2

Guys, why is my printf not getting the "time" of the struct? it is showing a random value. Follow the code below:

#include <stdio.h>
struct cadastro{
    char nome[30];
    int idade;
    int ano;
    int nmatricula;
    int tempo;
    float salario;
};
int main()
{
    int i;
    struct cadastro colaborador [2];
    for(i=0;i<2;i++){
    printf("Entre com o nome do colaborador: \n");
    scanf("%s",&colaborador[i].nome);
    printf("Entre com a idade: \n");
    scanf("%d",&colaborador[i].idade);
    printf("Entre com o numero da matricula: \n");
    scanf("%d",&colaborador[i].nmatricula);
    printf("Entre com o tempo na empresa: \n");
    scanf("%f",&colaborador[i].tempo);
    printf("Insira o salario: \n");
    scanf("%f",&colaborador[i].salario);
    printf("nome: %s\n",colaborador[i].nome);
    printf("idade %d\n",colaborador[i].idade);
    printf("numero da matricula %d\n",colaborador[i].nmatricula);
    printf("tempo na empresa %d\n",colaborador[i].tempo);
    printf("o salario foi %.2f\n",colaborador[i].salario);
    }
    return(0);
}
  • In the scanf, use %d for the reading of integers. %f is for floats. I believe this should solve

  • I don’t see you setting the values of the struct fields before using.

2 answers

0

When reading the value of colaborador[i].tempo, you use %f, which can only be used for Float type values. Since the Object property is declared as Int type, you must use %d. Remembering,

Char - <i>%c<i>
String - <i>%s<i>
Int - <i>%d<i>
Float - <i>%f<i>
Double - <i>%lf<i>

These are the most common primitive types of variables and their respective "codes".

-1

Hello! In your code I noticed 2 problems: 1- when a string is read in: "scanf("%s",&collaborator[i].name);" it is not used "&", since, you are not storing a specific character at a specific memory position but a character set at each vector position. 2 - with regard to the time at: "scanf("%f",&collaborator[i].tempo);", note that you used %f instead of %d or %i since in the structure the variable is of type int.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.