Conditional sex selector if

-1

How would you do in this code to get the person's gender and display in printf() ?

I've seen a lot of activities in the condition of if , if you used too many numbers and hit me a question: What if it was with letters?

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

int main()
{
  char sex[5], nome[200], f, m;

  printf("\n Digite o seu nome: " ); //pegar o nome da pessoa
  scanf(" %[^\n]s", &nome);

  printf("\n Digite seu sexo f ou m: "); //pegar o sexo da pessoa
  scanf("%s", &sex);

   if(sex == m)
    {
        printf(" bem vindo Senhor %s\n", nome); // se for homem
    }

   if (sex == f) 
    {
       printf(" Bem vinda Senhora %s\n", nome); // sefor mulher
    }

  else
   {
       printf("\n ERRO! \n");
   }

getchar();  
return 0;   
}
    
asked by anonymous 12.07.2018 / 01:36

3 answers

1

In this case you only need one character, you do not need more than this, as the code already shows. So it changes almost nothing.

#include <stdio.h>

int main() {
    char sex, nome[200];
    printf("Digite o seu nome: ");
    scanf(" %[^\n]s", nome);
    printf("\nDigite seu sexo f ou m:"); //pegar o sexo da pessoa
    scanf("%c", &sex);
    if (sex == 'm' || sex == 'M') printf("Bem vindo Senhor %s\n", nome);
    else if (sex == 'f' || sex == 'F') printf("Bem vinda Senhora %s\n", nome);
    else printf("\n ERRO! \n");
}

See running on ideone . And in Coding Ground . Also I put it in GitHub for future reference .

If you want to deal with the word you already have a answer about this . Another example .

    
12.07.2018 / 05:48
0

First

if(sex == m)
    {
        printf(" bem vindo Senhor %s\n", nome); // se for homem
    }

This mode of comparison is wrong. For the sex variable is a vector of char, or rather, string as you want to call it. This comparison == is for numbers (integers, float ...) or can use but m has to be 'm' and the sex has to specify the position of the vector to refer to the character itself; And its m and f are variable and have nothing in them, to use them would be necessary to make a scanf m or f or assign a character f = 'f' ...

You can use strcmp to compare for example:

if(strcmp(sex,'m')==0) 
{
printf(" bem vindo Senhor %s\n", nome); // se for homem
 }

Requirements:

To use strcmp it is necessary to use the #include < string.h > .

To improve your code:

scanf("%s", &sex);

You could only use getch() or getche() since the input is only a letter;

Requirements: To use the getch or getche function, you need to include the library conio.h in the program;

    
12.07.2018 / 01:42
0

You can do

char sex;

When you get the value use scanf("%c",&sex) or scanf("%s",&sex) and to compare you use if(sex == 'm') use single quotes as it is only one character.

#include <stdio.h>

int main() {
    char sex;
    printf("Digite seu sexo f ou m:");
    scanf("%c", &sex);

    if (sex == 'm') printf("Masculino");
}
    
12.07.2018 / 06:26