My function works but is missing one thing......

This function is part of a program that I wrote for an assignment. The other parts of the program work well but the vowel counting function only counts one vowel in the input and then stops. Im sure that the fix is easy, Im just drawing a blank at the moment. I was wondering if I need to write a loop in the function so it will continue to check every number or is it something else ?

Here it is:
1
2
3
4
5
6
7
8
9
10
11
12
//Function Name:"countVowels"===================================
int countVowels(string inputString)
{	
	int i=0;
	char letter;
	int vowels=0;
	letter= inputString [i];
	if (letter=='a' || letter=='e' || letter=='i' || letter=='o' || letter=='u'
	  ||letter=='A' || letter=='E' || letter=='I' || letter=='O' || letter=='U')
	++vowels;
	return vowels;
}
Your code only checks the string once for vowels. I would recommend something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <string>

using namespace std;

unsigned int countVowels (string& rstrLine)
{
    unsigned int unVowels = 0;
    unsigned int ui = 0;
    for (ui = 0 ; ui < rstrLine.size () ; ui++)
    {
	if (rstrLine [ui] == 'A' || rstrLine [ui] == 'a' ||
	    rstrLine [ui] == 'E' || rstrLine [ui] == 'e' ||
	    rstrLine [ui] == 'I' || rstrLine [ui] == 'i' ||
	    rstrLine [ui] == 'O' || rstrLine [ui] == 'o' ||
	    rstrLine [ui] == 'U' || rstrLine [ui] == 'u')
	{
	    unVowels++;
	}
    }
    return unVowels;
}

int main ()
{
    unsigned int ui = 0;
    string astrTest [4] ={
	"Hello World!!" , "GoodBye World!!" , 
	"Hey now brown cow!!" , "I don't like the lottery it is a tax on hope. --David Mitchell"
    };
    int anVowels [4] = {0};
    for (ui = 0 ; ui < 4 ; ui++)
    {
	anVowels [ui] = countVowels (astrTest [ui]); 
    }
    for (ui = 0 ; ui < 4 ; ui++)
    {
	cout << "Test #" << ui + 1  << " : " << astrTest [ui] << 
	    " , Has " << anVowels [ui] << " vowels." <<  endl;
    }
    return 0;
}
Last edited on
seems as though there's a little extra in there in there, eh?
bump
You are only checking the first char in the string. Use a loop to step through the whole string
This part:
1
2
3
4
letter= inputString [i];
	if (letter=='a' || letter=='e' || letter=='i' || letter=='o' || letter=='u'
	  ||letter=='A' || letter=='E' || letter=='I' || letter=='O' || letter=='U')
	++vowels;

has to be repeated for each letter of the string. Repetition can be handled by loops. In this case, the size of the string is known (C++ strings know their own size: http://www.cplusplus.com/reference/string/string/size/), so a for loop makes the most sense:
http://www.cplusplus.com/doc/tutorial/control/
Topic archived. No new replies allowed.