Why can not I read this character?

1

I'm new to programming; the question of the question is this:

  

Given as input data the name, height and sex (M or F) of a   person, calculate and show your ideal weight using the following   formulas:

     

• for males: ideal weight = (72.7 * height) - 58

     

• for female: ideal weight = (62.1 * height) - 44.7

However, in the code, it does not read the Male and Female data.

I wonder why I can not read?

Is scanf the best way to do character readings?

Thank you very much.

#include<stdio.h>#include<locale.h>#include<stdlib.h>#include<string.h>intmain(void){setlocale(LC_ALL,"");

    unsigned char nome[50],gen;
    float alt,resultado;


    printf("Qual o seu nome?\n");
    scanf("%s",&nome);

    printf("Qual o seu genero [M] ou [F] para feminino?\n");
    scanf("%c",&gen);

    printf("Qual a sua altura?\n");
    scanf("%f",&alt);

    if (gen == 'M') { 
        resultado == (72.7 * alt) - 58;
        printf("O seu peso ideal é: %.1f",resultado);
    } else if (gen == 'F') {
        resultado == (62.1 * alt) - 44.7;
        printf("O seu peso ideal é: %.1f",resultado);
    } else {
        printf("\n letra inválida, informe  M ou F\n");
    }
}
    
asked by anonymous 28.10.2017 / 20:28

1 answer

3

The function scanf automatically consumes blank spaces, before conversion, from the stdin input stream when the conversion specifier is not one of the following: %c , %n , and %[] .

This means that after

scanf("%s", nome); // remova '&', esse é o jeito correto de ler uma string com scanf

There is a line break character \n in the input stream, waiting to be consumed. Since your next command is

scanf("%c", &gen);

The scanf function will store the line break character in gen .

To resolve, use a blank space before the conversion specifier %c

scanf(" %c", &gen);

Whitespace tells the scanf function to skip the first whitespace, and the first character other than whitespace will be read with the %c conversion specifier.

In addition, both assignments to resultado are wrong. The assignment operator is only the character =

resultado = (72.7 * alt) - 58;
...
resultado = (62.1 * alt) - 44.7;
    
28.10.2017 / 21:35