Why Is My C Program Not Counting Vowels Correctly?

  • Thread starter Thread starter chmate
  • Start date Start date
  • Tags Tags
    Counting Program
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 6K views
chmate
Messages
37
Reaction score
0
Hi guys!

I made a program in C, which count vowels on text, but it doesn't work.
Thats the code i have writed:

Code:
#include <stdio.h>
#include <string.h>

int main()
{
  char buffer[80];
  int counter;

  printf("Enter a line of text: ");
  fgets(buffer, sizeof(buffer), stdin);
   
  for(counter=0; buffer[counter]!='\0'; counter++)
    {
      if(buffer[counter]=='a' && buffer[counter]=='e'
	 && buffer[counter]=='i' && buffer[counter]=='o'
         && buffer[counter]=='u') 
	continue;
    
      printf("In text, we have %d vowels", strlen(buffer[counter]));
      return 1;	
   }
   return 0;
}

Does anybody have an idea where is the problem?

Thanks.
 
Physics news on Phys.org
chmate said:
Hi guys!

I made a program in C, which count vowels on text, but it doesn't work.
Thats the code i have writed:

Code:
#include <stdio.h>
#include <string.h>

int main()
{
  char buffer[80];
  int counter;

  printf("Enter a line of text: ");
  fgets(buffer, sizeof(buffer), stdin);
   
  for(counter=0; buffer[counter]!='\0'; counter++)
    {
      if(buffer[counter]=='a' && buffer[counter]=='e'
	 && buffer[counter]=='i' && buffer[counter]=='o'
         && buffer[counter]=='u') 
	continue;
    
      printf("In text, we have %d vowels", strlen(buffer[counter]));
      return 1;	
   }
   return 0;
}

Does anybody have an idea where is the problem?

Thanks.
Well you are testing if a character from the buffer is 'a' AND 'e' AND 'i' AND 'o' AND 'u'. Of course that is impossible since it can only have one value.
Second where do you keep track of the number of vowels? You can't use counter for that since it is used to traverse the string. A faster way by the way would be to use pointer arithmetic to traverse the string.
Also don't you want to print your message after the for loop?
 
Last edited:
Code:
#include <stdio.h>
#include <string.h>

int
main()
{
        char buffer[80];
        int vowels = 0;

        printf("Enter a line of text: ");
        fgets(buffer, sizeof(buffer), stdin);

        int i;
        for(i = 0; buffer[i] != '\0'; i++){
                switch(buffer[i]){
                        case 'a': case 'e': case 'i': case 'o': case 'u':
                        case 'A': case 'E': case 'I': case 'O': case 'U':
                                vowels++;
                }
        }

        printf("In text, we have %d vowels\n", vowels);
        return 0;
}

Your program can not find capitals.