Comparison of char in C
I need to figure out whether or not each element of a chained list is a vowel.
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;
2
3 answers
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 on GitHub for future reference.
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, which is not the desired.
7
Author: Maniero, 2020-06-12 13:15:06
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;
}
3
Author: Lacobus, 2017-09-04 13:54:59
If you make this Your if so it works?
if(atual->letra == 'a' ||
atual->letra == 'e' ||
atual->letra == 'i' ||
atual->letra == 'o' ||
atual->letra == 'u'){
...
...
...
}
1
Author: gfleck, 2017-09-04 12:13:26