String comparison in C

-2

How could I print the variable sex out of if-else (it has to be OUT of it).

This code is printing blank and I can not understand why.

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

int main(void)
{

    setlocale(LC_ALL, "Portuguese");//habilita a acentuação para o português!

        int escolha;
        char sexo;


    printf("Escolha uma das opções abaixo: ");
    printf("\n1- Sou mulher ");
    printf("\n2- Sou homem ");
    scanf("%d", escolha);

    if(escolha==1){
        char sexo[]="Feminino";

    }
    else{
        char sexo[]="Masculino";
    }

    printf("Você é do sexo: ");
    printf(sexo);

return 0;   
}
    
asked by anonymous 20.10.2017 / 00:47

2 answers

5

You have some errors in the code including syntax. Solving these problems and organizing the code a bit you need to know is to use the strcpy() function to transfer the contents of the string to the vector.

There are better ways to do this, but to start learning is fine.

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

int main(void) {
    setlocale(LC_ALL, "Portuguese");
    int escolha;
    char sexo[11];
    printf("Escolha uma das opções abaixo: ");
    printf("\n1- Sou mulher ");
    printf("\n2- Sou homem ");
    scanf("%d", &escolha);
    if (escolha == 1) {
        strcpy(sexo, "Feminino");
    } else {
        strcpy(sexo, "Masculino");
    }
    printf("Você é do sexo: %s", sexo);
}

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

    
20.10.2017 / 00:55
0
First, you're declaring only char there at the beginning and using it as a vetor , you need to declare how many characters you'll use in its declaration, you can make a base of how many to use and place there (with one more to get the special character "string" indicating the end of strcpy(vetor de char, string a ser adicionada); ). Second, you are only matching char vectors, and this is not possible in C, for this you need to use the <string.h> function, of the one searched on the strcmp library that has many commonly used functions like %code% which compares strings and other very interesting ones as well.

    
20.10.2017 / 01:30