How to compare vectors in C

Asked

Viewed 3,943 times

2

Hi, I’d like to understand why my code doesn’t work. I’m trying to develop a forcible application and I can’t get the typed letter to be compared to the letter that’s in the vector, which I’m doing wrong?

Follows 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;
}
  • 2

    We can start here: char word[4]="rice"; you are trying to harvest 5 values in a vector with size 4

1 answer

4


There are some problems with your code:

  • char palavra[4]="arroz"; Reserved space does not play with 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 the if is comparing with == instead of assigning the value.

Besides, you’re reading a letter with gets as if it were a string and then in the comparisons use only the first caretere. Simplify and use only one char.

Nor does it have the end criterion that it should be when both strings are the same.

Settling all this would be 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 example in Ideone

Note that I used the function strcmp to compare words, which returns 0 when they’re equal.

Browser other questions tagged

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