Struct error reading second name

Asked

Viewed 17 times

0

Good afternoon, I’m doing a struct that stores name and age,the first step of the loop,but when it goes to read the second name it jumps,.

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

struct teste{
char nome[30];
int idade;
};

int main()
{

    struct teste teste2[2];
    int i;

    for(i=0;i<2;i++){
    printf("Digite Seu nome:");
    fgets(teste2[i].nome,30,stdin);
    printf("Digite sua idade:");
    scanf("%d",&teste2[i].idade);
    }
    for(i=0;i<2;i++){
    printf("Nome:%s",teste2[i].nome);
    printf("Idade:%d\n",teste2[i].idade);
    }





    return 0;
}
  • Clear the input buffer before reading the next name. He is taking the ' n' that was left in the input buffer and considering the name with zero characters. See has 12.18a of http://www.faqs.org/faqs/C-faq/faq/.

  • Thanks, it worked now

No answers

Browser other questions tagged

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