It’s no use just considering space, as done in your answer, because if a character like @
, %
or !
, it will be counted as consonant. For example, if the typed text is "a b c,!&defXYZ @ ABC"
, your code says there are 13 consonants (see), because you only considered that the spaces are not consonants, but the characters ,
, !
, &
and @
were considered in the count.
What you need to do is check if the character is actually a letter (and in the code below I’m only considering not accented letters of our alphabet), and then discard the vowels:
int main(void) {
char frase[30];
int consoantes = 0;
printf("Digite uma frase:");
scanf("%[^\n]",frase);
for (int i = 0; frase[i] != '\0'; i++){
char c = frase[i];
// se for maiúscula, converte para minúscula (excluí o "A", porque nesse caso nem precisa contabilizar)
if ('B' <= c && c <= 'Z') c += 32;
if ('b' <= c && c <= 'z') { // só testo se estiver neste intervalo
switch(c) { // como já deixei o "a" de fora, não preciso mais testar aqui
case 'e':
case 'i':
case 'o':
case 'u':
break; // se for vogal, não faz nada
default: // é consoante
consoantes++;
}
}
}
printf("A quantidade de consoantes na frase '%s' é %d\n", frase, consoantes);
return 0;
}
Now yes it correctly says that the string "a b c,!&defXYZ @ ABC"
has 9 consonants, see.
Notice that first I check if the char
is uppercase, and if so, I convert it to lowercase (just to facilitate the comparison that follows). To better understand how this works, give a read here. The detail is I’ve left the letter "a" out, so it’s one less letter to compare on switch
.
Finally, when the code arrives in the block switch
, at that point I’m sure the char
is a lowercase letter from "b" to "z". So I just increment the counter if it’s not a vowel (and by leaving the letter "a" out and converting before it to lowercase makes the switch
have fewer options to test, leaving the code more succinct - otherwise I would have to put 10 options case
: the 5 uppercase and lowercase vowels).
This is much simpler - and correct - than counting the number of vowels and counting the space as if it were a vowel (because it only works if the string has only letters and spaces, any other character is erroneously counted as a consonant).
Note that the way you did the sentence is swept several times (the
for(i=0;i<10;i++){
), and therefore any spaces are counted multiple times.– anonimo