anyone know why this error?

0

When I try to enter any value character the skip program in the option and I do not even have the chance to write somebody knows why?

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

    int i=0;
    struct pessoas {
    char nomealuno[60];
    int numeromeca;
    char rua[90];
    char curso[200];
    int dia;
    int mes;
    int ano;
    int nporta;
    int codigopostal1;
    int codigopostal2;
    int num;
    };

     .....

    case 1:
    {  
    printf("Nome    : "); 
    fgets(aluno[i].nomealuno, sizeof(aluno[i].nomealuno), stdin);

    printf("Numero mecanografico  : "); 
    scanf("%d",&aluno[i].numeromeca);

    printf("Data de nascimento    :\n "); 
    printf("dia.:");
    scanf("%d",&aluno[i].dia);  

    printf("mes.:");
    scanf("%d",&aluno[i].mes); 

    printf("ano.:");
    scanf("%d",&aluno[i].ano);

    printf("Rua   : "); 
    fgets(aluno[i].rua, sizeof(aluno[i].rua), stdin);

    printf("N da porta   :"); 
    scanf("%d",&aluno[i].nporta);

    printf("codigo postal:"); 
    scanf("%d",&aluno[i].codigopostal1); 
    printf("-");                                         
    scanf("%d",&aluno[i].codigopostal2);

    printf("Em que curso pertence o aluno?"); 
    fgets(aluno[i].curso, sizeof(aluno[i].curso), stdin);
    }

    .....

    
asked by anonymous 08.02.2018 / 23:31

1 answer

1

The problem is that scanf reads only the data that was entered and not the entered line break, which will only be what fgets will read next.

A robust solution is to read the integer also with fgets using a temporary buffer and sscanf :

char buff[20];
int numero;
fgets(buff, sizeof(buff), stdin); //lê como string
sscanf(buff, "%d", &numero); //interpreta o inteiro na string lida

If you want to simplify, you can even do a function to encapsulate this logic whenever you need to read only one number:

char buff[20];

int lerInt(){
    int numero;
    fgets(buff, sizeof(buff), stdin);
    sscanf(buff, "%d", &numero);
    return numero;
}

Applying this logic your code would look like this:

printf("Nome    : ");
fgets(aluno[i].nomealuno, sizeof(aluno[i].nomealuno), stdin);

printf("Numero mecanografico  : ");
aluno[i].numeromeca = lerInt();

printf("Data de nascimento    :\n ");
printf("dia.:");
aluno[i].dia = lerInt();

printf("mes.:");
aluno[i].mes = lerInt();

printf("ano.:");
aluno[i].ano = lerInt();

printf("Rua   : ");
fgets(aluno[i].rua, sizeof(aluno[i].rua), stdin);

printf("N da porta   :");
aluno[i].nporta = lerInt();

printf("codigo postal:");
aluno[i].codigopostal1 = lerInt();
printf("-");
aluno[i].codigopostal2 = lerInt();

printf("Em que curso pertence o aluno?");
fgets(aluno[i].curso, sizeof(aluno[i].curso), stdin);

See the code running on Ideone

    
09.02.2018 / 01:35