Comparison of char in C

Asked

Viewed 16,313 times

2

I need to find out if each element of a chained list is a vowel or not.

How can I fix my code?

int BuscaNv(LISTA* resp){
   NO* atual = resp->inicio; 

   while(atual){
    if(atual->letra == 'a' || 'e' || 'i' || 'o' || 'u'){
      printf("É vogal\n");
      atual = atual->prox;
    }
    else{
      printf("Não é vogal\n");
      atual = atual->prox;
    }
   }
   return 0;
}

Typedefs:

typedef struct estr {
    char letra;
    struct estr *prox;
} NO;

typedef struct {
    NO *inicio;
} LISTA;
  • Why aren’t you getting it?

  • Code returns "is vowel" for all characters

  • These || are wrong.

  • Behold, this publication. The problem is the same as yours, what changes is the syntax of the language.

3 answers

7


This syntax is completely wrong, you have to compare the variable against the character individually.

if (atual->letra == 'a' || atual->letra == 'e' || atual->letra == 'i' || atual->letra == 'o' || atual->letra <= 'u')

I put in the Github for future reference.

I was comparing the first Boolean expression against characters. A character that is not null is a value other than 0, and in Boolean logic 0 is false and all other values are true, so already in the second expression after the || will always give true, that is not the desired.

3

How about using a function to check if the letter is a vowel:

int eh_vogal( char c )
{
    int i = 0;
    static const char v[] = "aeiouAEIOU";

    while( v[i] )
        if( v[i++] == c )
            return 1;

    return 0;
}

With that, your code would look like this:

int BuscaNv(LISTA* resp){
    NO* atual = resp->inicio;

    while(atual){
        if(eh_vogal(atual->letra)){
            printf("É vogal\n");
            atual = atual->prox;
        }
        else{
            printf("Não é vogal\n");
            atual = atual->prox;
        }
    }
    return 0;
}

1

If you do this if how it works?

    if(atual->letra == 'a' ||
       atual->letra == 'e' ||
       atual->letra == 'i' ||
       atual->letra == 'o' ||
       atual->letra == 'u'){
    ...
    ...
    ...
    }
  • 1

    The @bigown response is more complete.

Browser other questions tagged

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