-2
When executing the code below, choosing the option 2 the name is entered "Teste Nome", the struct pessoas[i].nome gets the value Teste Nome\n\000 shortly after the fgets(). However, after the scanf() (which is used to punctuate the struct pessoas[i].idade), the struct pessoas[i].nome gets the value \000\000\000te Nome\n\000
Please, can anyone tell me where I went wrong? I can’t find the bug at all.
#include<stdio.h>
#include <conio.h> // para leitura do nome
#define MAX 1
#define MAX_NOME 50
struct pessoa{
char idade;
char nome[MAX_NOME];
};
void main(){
short opcao;
struct pessoa pessoas[MAX];
int i;
do {
printf("\n2 - Carregar os dados manualmente\n");
printf("6 - Exibir todas as pessoas\n");
printf("0 - S A I R\nOpcao: ");
fflush(stdin);
scanf("%d", &opcao);
switch(opcao) {
case 2: // Carregar os dados manualmente
for (i = 0; i < MAX; i++) {
printf("Nome: ");
fflush(stdin);
fgets(pessoas[i].nome, MAX_NOME, stdin);
printf("Idade: ");
scanf("%d", &pessoas[i].idade);
}
break;
case 6: //Exibir todas as pessoas
for (i = 0; i < MAX; i++) {
printf("Idade: %2d - Nome: %s\n", pessoas[i].idade, pessoas[i].nome);
}
break;
case 0: //S A I R
// Nao faz nada
break;
default:
printf("\nOpcao invalida\n");
break;
}
} while(opcao != 0);
}
fflush(stdin)generates undefined behavior, then it is not recommended to use (and even if it did, it should be called after thescanf, not before). Anyway, the problem is mixingscanfandfgets, take a look here and here. And why age is onecharand not aint?– hkotsubo
@hkotsubo thanks for the guidelines. I read all the shared links. In fact, the age variable was with the wrong type. I switched to short. However, even with all this the system did not work. Although my question won one (-2), I asked many questions before coming here. What solved the bug itself was the scanf() that was being used erroneously. I’ll answer my own question so other people can see someday.
– Satoru Kishi