0
Hello!
I am Newbie and I am trying to make a program to read a list of information inserted in it.
Until the first line it works, but from the second register he no longer reads the name, putting the second text "SEXO: [M/F]
" in the name line and the end result does not exit as expected.
Follows the code:
#include <stdio.h>
#include <locale.h>
#include <stdlib.h>
int main (void) {
setlocale(LC_ALL, "Portuguese");
// <.Listagem de Cadastrados.>
char nome1[40], nome2[40], nome3[40];
char sexo1,sexo2, sexo3;
float nota1,nota2,nota3;
printf("Cadastrando 1° pessoa\n");
printf("--------------------------\n");
fflush(stdin);
printf("NOME: ");
fgets(nome1,40,stdin);
printf("SEXO [M/F]: ");
sexo1 = getchar();
printf("NOTA: ");
scanf("%f", ¬a1);
printf("--------------------------\n");
printf("Cadastrando 2° pessoa\n");
printf("--------------------------\n");
fflush(stdin);
printf("NOME: ");
fgets(nome2,40,stdin);
printf("SEXO [M/F]: ");
sexo2 = getchar();
printf("NOTA: ");
scanf("%f", ¬a2);
printf("--------------------------\n");
printf("Cadastrando 3° pessoa\n");
printf("--------------------------\n");
fflush(stdin);
printf("NOME: ");
fgets(nome3,40,stdin);
printf("SEXO [M/F]: ");
sexo3 = getchar();
printf("NOTA: ");
scanf("%f", ¬a3);
system("clear"); // limpar tela - mesma ideia do cls no windows.
printf("Listagem Completa\n\n");
printf("------------------------------\n");
printf("NOME SEXO NOTA");
printf("%s %c %.2f\n",nome1,sexo1,nota1);
printf("%s %c %.2f\n",nome2,sexo2,nota2);
printf("%s %c %.2f\n",nome3,sexo3,nota3);
printf("------------------------------\n");
}
Could you help me understand this problem? Could suggest improvements in code?
Att.
Everything worked fine, but at the end (the printf of the result) n is all on the same line; the name stays on one and the other information stays on the other. Knows how to solve?
– hiyan
The fgets function keeps the ' n' which indicates the end of the input as part of the string read (if the size of the string read is less than the maximum indicated in the function call). One possibility is to verify that the last character of the string read is effectively ' n' and is replaced by ' 0'. Search here for answers that you will find suggestions on how to solve.
– anonimo
I managed to solve, I really appreciate the support!
– hiyan