Break line when typing entries

Asked

Viewed 1,889 times

2

I have a vector of structs with 10 people and I want my registration function to receive only one person at a time.
In the terminal, the register of the first person is made correctly but then I get this "break" line, jumps alone from the name I would type to the age. Why this occurs?

[danielamorais@localhost Desktop]$ ./ex3
Digite o nome:
Daniela
Digite a idade:
18
Digite o nome:
Digite a idade:

Code

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


#define TAM 10

typedef struct{
char nome[30];
int idade;
} Pessoa;

void cadastrarPessoa(Pessoa *pessoa){
        puts("Digite o nome:");
        gets((*pessoa).nome);
        puts("Digite a idade:");
        scanf("%d", &((*pessoa).idade));
}

void lerPessoas(Pessoa *p){
    for(int i = 0; i < TAM; i++){
        cadastrarPessoa(&p[i]);
    }
}

void imprimirVetor(Pessoa *p){
    for(int i = 0; i < TAM; i++){
        printf("Nome: %s", p[i].nome);
        printf("Idade: %d", p[i].idade);
    }
}

void main(){
    Pessoa *pessoa = (Pessoa *)malloc(sizeof(Pessoa) * TAM);
    lerPessoas(pessoa);
    imprimirVetor(pessoa);
}
  • Vc is on linux or windows?

  • @Denercarvalho Fedora 23

1 answer

3


To fix the problem of skipping line it is necessary to clear the keyboard buffer with the __fpurge which is left by scanf, look at the modifications:

void cadastrarPessoa(Pessoa *pessoa){
        puts("Digite o nome:");
        gets((*pessoa).nome);
        puts("Digite a idade:");
        scanf("%d", &((*pessoa).idade));
        __fpurge(stdin);/*<-------Mudei aqui*/
}

It is necessary to declare the library stdio_ext.h to use the __fpurge, suggest changing the gets for fgets, because the gets and vulnerable to bufferoverflow.

The i does not declare itself within the for, have to stay out, see:

int i;
for (i = 0; i < 10; i++){faz algo....}
  • 1

    It worked, thanks! And as for the declaration of i, does it not vary according to the compiler? Some compile normally and others do not.

  • gcc does not accept, I think only g++ that is c++ that allows declaring variables within for and while.

Browser other questions tagged

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