2
I always used the fgets() function to read keyboard strings, because it (at least I thought so) always clears the input buffer. However, I am finding some errors with the execution of the function in the case of the code below. The strings are not being read correctly, it’s like I’m using scanf("%c") and picking up trash from the input buffer.
PS: I know fflush(stdin) cleans the input buffer, but I don’t like using this function because it is not portable.
The struct I’m intending to read in function:
struct Participante
{
char nome[40];
char cpf[11];
char email[20];
char matricula[15];
char nascimento[8];
int ocupacao;
};
The function:
participante* entrada_dados()
{
participante *part;
char c;
part = (participante*) malloc(sizeof(participante));
printf("Digite o nome do participante \n");
fgets(part->nome, sizeof(part->nome), stdin);
printf("Digite o CPF do participante \n");
fgets(part->cpf, sizeof(part->cpf), stdin);
printf("Digite o email do participante \n");
fgets(part->email, sizeof(part->email), stdin);
printf("Digite a matricula do participante \n");
fgets(part->matricula, sizeof(part->matricula), stdin);
printf("Digite a data de nascimento do participante no formato DDMMAAAA \n");
fgets(part->nascimento, sizeof(part->nascimento), stdin);
printf("Digite a ocupacao do participante: \n 1- Professor \n 2- Estudante \n");
scanf("%d", &part->ocupacao);
return part;
}
Ps2: I am using pointer to structure, because I will return the allocated address and use for the construction of a chained list.
Example of screen with error:
You have the call to duty
entrada_dados()
in a certain cycle?– pmg
That. There is a menu in main and while informing option 1 the input() function is called.
– Vinicius
You can try to clear the input buffer before the first
printf
of functionentra_dados()
withfflush(stdin);
.– DaviAragao