Home > other >  I am getting wrong result for this simple vowel counter
I am getting wrong result for this simple vowel counter

Time:12-15

i am trying to get the number of vowels, but it prints the wrong number most of the time, for example i inputed "ccc" but got "vowel=2"? what exactly did i do wrong?

#include <stdio.h>

int main()
{
    char word[20];
    int vowel=0;
    puts("enter word to check number of vowels");
    fgets(word,sizeof(word),stdin);
    for (int character=0;character<sizeof(word);character  )
     {
         if (word[character]=='a'||word[character]=='e'||
            word[character]=='i'||word[character]=='o'||
            word[character]=='u'||word[character]=='A'||
            word[character]=='E'||word[character]=='I'||
            word[character]=='O'||word[character]=='U')
                vowel  ;
     }
     printf("vowels=%d",vowel);
}

CodePudding user response:

You're using the wrong thing to get the length of the string. sizeof(word) is the size in bytes of the entire buffer. However, fgets did not initialize all those values so you have undefined behavior.

Use strlen(word) to get the length of a string.

Note you could also simplify your vowel test:

if (strchr("aeiouAEIOU", word[character])) vowel  ;

CodePudding user response:

Rather than iterate to the size of the buffer, iterate to the end of the input string. No need to call strlen(), just look for the null character.

// for (int character=0;character<sizeof(word);character  )
for (int character=0; word[character]; character  )

Test fgets() result to insure something was read. fgets() returns NULL when nothing was read or an input error.

// fgets(word,sizeof(word),stdin);
if (fgets(word, sizeof word, stdin)) {
  for (int character=0; word[character]; character  )
  ...
} 
  • Related