Beginner: counting number of vowels; program not working properly.

Hi, I am writing a program in which, the user inputs a sentence of 100 characters max ending with a '.'. Then the program outputs the number of vowels found in the sentence.

I wrote the program, but I'm not getting the appropriate result (i.e. the correct number of vowels).

[I am wondering if any1 can inspect the code and tell me whats wrong, since i'm new to this stuff].


# include <iostream>
# define size 100

using namespace std;


int main()
{
char sentence[size];
char vowels[]={'a','e','i','o','u'};
int n,i, count = 0;


cout << "Please insert a sentence: ";
cin.getline(sentence,size, '.');

for(n=0; n<size; ++n)
{
for(i=0; i<6; ++i)
{
if (vowels[i]==sentence[n])
{
count+=1;
}
}
}

cout << "number of counted vowels: " << count;
return 0;
}
you go through 100 chars of sentence even if there were less. use strlen( sentence ) to know how many chars there are.
you go through vowels 0-5 (6 values) even though there are only 5.
you go through 100 chars of sentence even if there were less. use strlen( sentence ) to know how many chars there are.
you go through vowels 0-5 (6 values) even though there are only 5.


You need to add library cstring for strlen. Also you are not checking if the sentence has upper cased vowels. (your vowels array consists only of lower cased vowels.) I dont know if this is a requirement or not. This is also a probable reason for count mismatch.

use inbuilt library func tolower while comparing.
These are the probable additions / modifications:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <cstring>

...
...

for(n = 0; n < strlen(sentence); n++) {
for(i = 0; i < 5; i++) {
if (vowels[i] == tolower(sentence[n])) 

// remaining part is same 
Many Thanks. My problem is solved. ;-)
Topic archived. No new replies allowed.