Comparison of char in C

2

I need to find out if each element in a linked 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;
    
asked by anonymous 04.09.2017 / 14:01

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 was comparing the first boolean expression against characters. A non-null character 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 || will always give true, which is not the desired one.

    
04.09.2017 / 14:11
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 this, 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;
}
    
04.09.2017 / 15:54
1

If you do this if yours works like this?

    if(atual->letra == 'a' ||
       atual->letra == 'e' ||
       atual->letra == 'i' ||
       atual->letra == 'o' ||
       atual->letra == 'u'){
    ...
    ...
    ...
    }
    
04.09.2017 / 14:13