counting vowel in a string

1
2
3
4
5
6
7
8
9
10
11
12
13
int vowelcount (char[],int,int) 
{
int vow_cnt=0;
for(int i=0;i<strlen[];i++)
{
if(name[i] == 'a' || name[i] == 'e'||name[i] == 'i'||name[i] == 'o'||name[i] == 'u')
{
vow_cnt++;
return vow+cnt;
}



can u guys find something wrong i cant .its a recursive function that count vowels in a given string .
thanks
Last edited on
This is how I'd implement a program that searches a string for vowels:

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
#include<iostream>
using namespace std;

int main(){
	
	char blah[] = "blah";
	int index = 0;
	int vowel = 0;

	while (blah[index] != '\0') {
		switch (blah[index]) {
		case 'a':
			vowel++;
			break;
		case 'e':
			vowel++;
			break;
		case 'i':
			vowel++;
			break;
		case 'o':
			vowel++;
			break;
		case 'u':
			vowel++;
			break;} index++;}

	cout << "Number of vowels was " << vowel;

	while (true) {}

	return 0;}
1
2
3
4
5
6
7
8
9
10
11
12
int vowelcount (char[],int,int) // Lacking names for the variables
{
    int vow_cnt=0;
    for(int i=0;i<strlen[];i++) // strlen should be an int, making strlen[] an invalid operation
    {
        if(name[i] == 'a' || name[i] == 'e'||name[i] == 'i'||name[i] == 'o'||name[i] == 'u')
        {
        vow_cnt++;
        return vow+cnt;
        }
// } missing bracket
// } missing bracket  

You're lacking a large number of brackets.
The variables are lacking names, most likely char[] name and int strlen (the last int does not seem to be used.
strlen should be an int.
you're returning vow+cnt which is undefined, you mean vow_cnt.
Finally you're returning inside the for loop instead of at the end, meaning it'll return once it's found the first vowel.
here is another way, a simple function:

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
#include<iostream>
#include<cstring>
using namespace std;

int vCount ( char *);

int main(){

	char word[80];
	cout << "enter a line:";
	cin.getline (word, 80);
	cout << "vowel count: " << vCount(word) << endl;

return 0;
}

// returns the number of vowels in a char array
int vCount ( char * pCh){
	int vowels = 0;

	while(*pCh){
		if(strspn(pCh, "aeiou"))
			vowels++;
		pCh++;
	}

	return vowels;
}

/*
sample output:
enter a line: count the vowels in this sentence
vowel count: 10

*/
Last edited on
Topic archived. No new replies allowed.