The code skips the fgets, not reading the word

Asked

Viewed 694 times

0

The program is not reading mine fgets() getting there he jumps.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    float altura, peso,pesoidealm,pesoidealf;

    char sexo[10];

    printf("Digite sua altura\n");
    scanf("%f",&altura);

    printf("Digite seu peso\n");
    scanf("%f",&peso);

    printf("Digite seu sexo\n");
    fgets(sexo,9,stdin);

    pesoidealm=(72.7*altura)-58;
    pesoidealf=(62.1*altura)-44.7;

    if(!(strcmp(sexo,"masculino")))
    {
        printf("Peso Ideal:%f\n",pesoidealm);
    }
    system("PAUSE");
    return 0;
}
  • And do you need to type in all the sex? Can’t it just be the initial like everyone else does? And it needs to be with fgets()?

  • It is that this asking in the exercise. And how to use gets (can give bufferoverflow), so I think the best to use is fgets().

  • And why not scanf() even?

  • I think it’s because it’s a string.

3 answers

5

The simple way to do this is to use the scanf() even so in a simpler way and organized in the code:

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

int main() {
    float altura, peso;
    char sexo[10];
    printf("Digite sua altura\n");
    scanf("%f", &altura);
    printf("Digite seu peso\n");
    scanf("%f", &peso);
    printf("Digite seu sexo\n");
    scanf("%9s", sexo);
    if (!strcmp(sexo, "masculino")) printf("Peso Ideal:%f\n", (72.7 * altura) - 58);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

3


Being direct, use getchar(); before calling fgets. The code would look like this:

printf("Digite sua altura\n");
scanf("%f",&altura);
printf("Digite seu peso\n");
scanf("%f",&peso);
printf("Digite seu sexo\n");

getchar();

fgets(sexo,9,stdin);
  • Damn, thank you very much!!!

  • This is because when you press ENTER after you enter the weight, a ' n' is stored in the input stream. getchar() will consume this character and prevent it from being immediately passed to fgets

2

In my case, I decided to just clean the buffer:

char nomeJogador1[32];

setbuf(stdin, 0);

printf("Nome do 1° jogador: ");
fgets(nomeJogador1, 32, stdin);

Browser other questions tagged

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