Returning (Null) when displaying a variable String

0

The program should receive a person's name and gender and show the data entered by the user, but when the program shows the name I typed it is appearing Null instead of showing the name.

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

main()
{
    setlocale(LC_ALL, "Portuguese");
    char nome, sexo;

    printf("Digite o seu nome: ");
    scanf("%s", &nome);
    printf("Digite o seu sexo M (Masculino) ou F (Feminino): ");
    scanf("%s", &sexo);

    if(sexo=='f' || sexo=='F')
    {
        printf("\nOlá %s o seu sexo é feminino.\n\n", nome);
    }else

    if(sexo=='m' ||sexo=='M')
    {
        printf("\nOlá %s o seu sexo é masculino.\n\n", nome);
    }else

    if(sexo!='f' || sexo!='F' || sexo!='m' || sexo!='M')
    {
        printf("Sexo inválido");
    }

    system("pause");
}

    
asked by anonymous 27.09.2018 / 16:54

3 answers

2

sexo is of type char , okay, just one character to store it, at least in the form used. But there is an error reading it. To read a given char %c no scanf() .

Already in the name you are using the correct formatting in scanf() , but you are using the wrong type in the variable. A name must be a string , so a string if characters terminated by a null. You are only getting the null because you have not declared the variable as a string but as a single character.

To declare a string we use a pointer or an array . In this case I find it more appropriate for an array to reserve the space for the whole variable. So it would be something like char nome[31] . You do not even need to pass the address because an array is already a memory address, it's already a reference.

More organized, the code looks like this:

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

int main() {
    setlocale(LC_ALL, "Portuguese");
    char nome[31];
    char sexo;
    printf("Digite o seu nome: ");
    scanf("%30s", nome);
    printf("Digite o seu sexo M (Masculino) ou F (Feminino): ");
    scanf("%c", &sexo);
    if (sexo == 'f' ||  sexo == 'F') printf("\nOlá %s o seu sexo é feminino.", nome);
    else if (sexo == 'm' || sexo == 'M') printf("\nOlá %s o seu sexo é masculino.", nome);
    else printf("Sexo inválido");
}
    
27.09.2018 / 17:01
1

You are declaring nome to be char :

char nome, sexo;

There are two alternatives. The first is to declare the variable as a vector , where it will define the maximum size of characters that it can store; another is to use a pointer , making it more dynamic.

//opção usando vetor
char nome[256];
//opção usando ponteiro
char *nome;
    
27.09.2018 / 17:01
1

You have to declare char as a vector:

char[numero] nome;
    
27.09.2018 / 22:38