3
/* Write an algorithm that reads data from "N" people (name, sex, age and health) and indicate whether you are fit or not to fulfill the mandatory military service. Inform the totals. */
#include <stdio.h>
#include <stdlib.h>
struct Pessoa
{
char nome[30];
char sexo[1]; // M = Masculino e F = Feminino
int idade;
char saude[5];
};
main()
{
int quant; // Quantidade de pessoas
printf("Digite a quantidade de pessoas: ");
scanf("%d", &quant);
struct Pessoa candidato[quant];
int i;
for(i = 0; i < quant; i++)
{
printf("\nNome: ");
fgets(candidato[i].nome,30,stdin);
printf("\nSexo: ");
fgets(candidato[i].sexo,1,stdin);
printf("\nIdade: ");
scanf(" %d", &candidato[i].idade);
printf("\nSaude: ");
fgets(candidato[i].saude,5,stdin);
if(candidato[i].idade >= 18 && candidato[i].saude == "boa")
{
printf("O %s, sexo %s com idade %d e com saude %s esta apto ao servico militar. \n\n",
candidato[i].nome, candidato[i].sexo, candidato[i].idade, candidato[i].saude);
}
printf("\n\n");
} // fim do for
} // fim função main()
But when I use the fflush
shows "Name: Sex" (in the same line) how do I resolve this?
What is your doubt?
– Felipe Avelar
The
fflush(stdin)
is defined in Windows. Other systems do not work. If you want a portable solution you should try to find another solution.– pmg
When I use fflush does not show type Name: Sex (in the same line) how do I resolve it then?
– phpricardo
The simplest solution will be to use
fgets()
for all inputs. Then, in specific cases, convert the string to integer withsscanf()
.– pmg
fgets() codeblocks does not work. :(
– phpricardo
There is no point in you declaring sex[1];. When you declare a string you need to predict the terminator character ('0') and if you only predict the 1 size then there is no space for it. Note that char sex; (the variable has space for a character) is quite different from char sex[1]; (a string of length 1). When doing gets(candidate[i]. sex); you will put the ' 0' out of the allocated area for the variable. Use char sex; and scanf("%c", &sex);.
– user4552
In the future, when you have a similar question, do not forget to beg what error you are making, what input you are going through, what exit you wanted, etc. It is much more difficult to give a good answer if you just say that "it is not working right"
– hugomg
If fgets did not work it is because you made some mistake in its use, probably erroneously specified its parameters. See details in: http://pubs.opengroup.org/onlinepubs/000095399/functions/fgets.html
– user4552
I’m sorry, I’ve been busy with other things. But I’m still unsuccessful in this program, keeps showing the three questions at once. Name: Sex: age in the same line.
– phpricardo