Language C - Structure jumps directly to ELSE ignoring IF parameters

Asked

Viewed 270 times

-4

#include<stdio.h>

int main(){

    //Escolhe entre nome do personagem e classe

    int p,c;
    printf("RPG teste\n");

    printf("Digite um nome para o seu(a) personagem:");
    scanf("%s",&p);
    printf("Escolha uma classe, digitando entre Guerreiro ou Monge:");
    scanf("%s",&c);

    if (c=="Guerreiro"){
        printf("Guerreiro");
    }
    else
    {
        printf("Monge");
    }
    system("pause");
}
  • You are trying to compare a string to a number, so you will always enter Else

  • 1

    Please don’t vandalize the questions. There is no reason to exclude the question, even because it was well accepted and has well accepted answers. The question does not belong to the user, belongs to the community, if you have particular reason to remove the link from your profile with the question, contact the SE directly and report your case to be analyzed

2 answers

5


You have to revise a little the concepts in C, there are some "mistakes" in your code, as:

  • The variables p and c are declared as int, but in the code are used to keep a word.

When you use int, you are specifying that the variable will receive an integer number, that is, you cannot save other types of data, and you cannot save a word, for example. For this you can specify a type variable char (string), which will save a total number of characters, for example:

char variavel[50];
  • In the structure of if, you try to compare c directly with the word "warrior".

Even if you set the variable type to char(string), as in the example above and try to make a if direct comparison, would give "error", it will never enter the condition of if, because it is not possible to directly compare a variable of type char(string). Save exception, where char is used to store a single character, for example:

#correto
char variavel;
variavel = 'a';
if(variavel == 'a');

#incorreto
char variavel[20];
variavel = "palavra";
if(variavel == "palavra");

When used only char variavel, you can save a single character, allowing you to make a comparison in a if normal with single quotes 'a', but when using char variavel[20], you are declaring a string that can store a number of characters in it, depending on the value you specify in the assignment.

In this case the comparison is different, there is a function in the library <string.h> that makes this comparison, this function is the strcmp(), that you can see a better explanation on that page. Basically, it returns a number depending on the situation of the comparison, being able to verify if it is greater, equal or smaller:

c = "variavel";
if(strcmp(c, "variavel") == 0); #a função retorna 0, pois são iguais

So you can make a comparison between two words.

  • Utilise scanf() to read words.

Although it works, it is not the most appropriate to use the scanf() to read words, as it will not be able to read a compound name, for example:

scanf("%s", variavel); #foi digitado o nome José Maria
printf("%s", variavel); #imprime somente o nome José

So the most appropriate thing in this situation is to use the gets(), that will store everything that is typed, you can read more about it here.

Last but not least, is the complete code of how it should be:

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

main(){
    char p[20];
    char c[20];
    printf("RPG TESTE\n");
    printf("Digite um nome para o seu(a) personagem:");
    fflush(stdin);
    gets(p);
    printf("\nEscolha uma classe, digitando entre Guerreiro ou Monge:");
    fflush(stdin);
    gets(c);
    if(strcmp(c, "Guerreiro") == 0){
        printf("\n\nGuerreiro");
    }
    else {
        printf("\n\nMonge");
    }
}
  • 1

    The code compiled perfectly, thank you for explaining

1

Hello, Danilo! Welcome back!

The solution to your problem involves some important concepts of structured programming C.

A variable is a space in memory. It has name, address and can store a value.

When declaring a variable, you must specify the type of variable you want.

  • int: integer values (-2, 0, 1)
  • float: floating values (-3.5, 1.0, 5.33)
  • double: large floating values (3.1415926535897932384626433832795)
  • char: characters ('a', 'b', 'c')
  • bool: boolean values (true, false)

When you want to store a word (string, string), One must use a vector. Vector is a sequence of spaces in memory. Each space is called an index, which starts from 0 (zero). The zero index is the default vector address.

char nome[4];
nome[0] = 'A';
nome[1] = 'N';
nome[2] = 'A';
nome[3] = '\0';

The value '\0' is used to indicate the end of the string, so it is necessary to reserve an extra space in the vector.

There are other ways to initialize a string.

char nome[] = "ANA";
char nome[4] = "ANA";
char nome[4] = {'A','N','A'};
char nome[10] = "ANA";

Solitary characters are assigned between single quotes '', whereas strings are assigned between double quotes "".

The library stdio.h has read functions (input by keyboard) scanf(arg_1, arg_2) and writing (screen output) printf(arg_1, arg_3).

Each function has two arguments, but there are 3 types of arguments in this case.

  • arg_1: value formatting
  • arg_2: memory space address
  • arg_3: name of memory space

To read or write a value, the format of that value must be specified.

  • %d: integers and booleans (1 - true, 0 - false)
  • %f: floating
  • %Fl: large floating
  • %c: character
  • %s: string

Note that boolean variables return 1 or 0, so they share the same format specifier as integers. For floaters in particular, it is possible to specify the number of boxes before and after the point, for example: %2.3f for numbers 0.333, 25.587, 4.444.

int num = 0;
scanf("%d", &num);
printf("numero: %d\n", num);

char nome[10];
scanf("%s", nome);
printf("nome: %s", nome);

Note that to read an integer value from the keyboard, the given address was &num ("e" commercial followed by variable name). Already to read a string, the address provided was nome (only the name of the vector). This is done because the address of the vector is linked to the name of the vector itself, pointing to the zero index of the vector.

Now we come to the solution of the problem in question.

To compare whether two strings are equal, it is necessary to use the operation function of string strcmp(string_1, string_2) present in the library string.h.

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

    int main(){

        //Escolhe entre nome do personagem e classe

        char p[20];
        char c[20];
        printf("RPG teste\n");

        printf("Digite um nome para o seu(a) personagem:");
        scanf("%s",p);
        printf("Escolha uma classe, digitando entre Guerreiro ou Monge:");
        scanf("%s",c);

        if (strcmp(c,"Guerreiro") == 0){
            printf("Guerreiro");
        }
        else
        {
            printf("Monge");
        }
        return 0;
    }

Bonus: Another function of the string. h library that may be useful is strcpy(Nome, "nome de alguém").

  • Thanks for the explanation, I will study the points indicated. The code compiled perfectly

  • You’re welcome, my boy! :)

Browser other questions tagged

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