String comparison in C

Asked

Viewed 452 times

-2

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

This code is printing blank and I can’t 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;   
}
  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

2 answers

5

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

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

#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);
}

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

0

First, you are declaring only one char there at the beginning and using it as a vetor, you need to declare the amount of characters you will use in his statement, you can make a base of how many you will use and put there (with one more to get the special character \0 indicating the end of "string"). Second, you’re just matching char vectors, and that’s not possible in C, so you need to use the function strcpy(vetor de char, string a ser adicionada);, of a survey on the library <string.h> that there have several functions very used as the strcmp that compares strings and other very interesting ones as well.

Browser other questions tagged

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