How to compare vectors in C

2

Hello, I would like to understand why my code does not work. I'm trying to develop a galaxy application and I can not seem to get the letter typed to be compared to the letter in the vector, what am I doing wrong?

Follow the code:

#include<stdio.h>
#include<locale.h>
#include<time.h>
#include<stdlib.h>
#include<string.h>
int main (){
    int i,len_palavra,exec=1,back;
    char lacuna[20]="_";
    char letra[20];
    char palavra[4]="arroz";

    setlocale(LC_ALL,"PORTUGUESE");
    len_palavra = strlen(palavra);
    for(i=1;i<=len_palavra;i++)
    lacuna[i]='_';

    while (exec == 1){
        system("cls");
    printf("\t\t%s\n",lacuna);
    printf("\nDigite uma letra: ");
    gets(letra);

    for(i=0;i<len_palavra;i++){
        if (letra[0] == palavra[i])
            lacuna[i] == letra[0];
    }
}
    return 0;
}
    
asked by anonymous 18.10.2017 / 20:23

1 answer

4

You have some problems with your code:

  • char palavra[4]="arroz"; The placeholder does not play with the saved size

  • for(i=1;i<=len_palavra;i++) This for is with <= instead of < only

  • if (letra[0] == palavra[i]) lacuna[i] == letra[0]; Within if is comparing with == instead of assigning value.

In addition, you are reading a letter with gets as if it were a string and then in comparisons you use only the first letter. Simplify and use only char .

It also does not have the end criterion that should be when both strings are equal.

Fixing all this would look like this:

int main ()
{
    int i,len_palavra;
    char lacuna[20]="_";
    char letra; //apenas char
    char palavra[]="arroz"; //sem tamanho especificado

    setlocale(LC_ALL,"PORTUGUESE");

    len_palavra = strlen(palavra);
    for(i=1; i<len_palavra; i++) //apenas com <
        lacuna[i]='_';

    while (strcmp(palavra,lacuna) != 0) //strcmp para saber quando termina
    {
        system("cls");
        printf("\t\t%s\n",lacuna);
        printf("\nDigite uma letra: ");
        scanf("%c",&letra); //scanf com %c em vez de gets

        for(i=0; i<len_palavra; i++)
        {
            if (letra == palavra[i])
                lacuna[i] = letra; //atribuição em vez de comparação
        }
    }

    printf("\t\t%s\n",lacuna); //adicionei este printf para ver o estado final do jogo
    return 0;
}

See the Ideone example

Note that I used strcmp to compare words, which returns 0 when they are equal.

    
18.10.2017 / 21:03