You are here:

C++/Vowel Count using Recursion


I know how to count vowels of a string using recursion, but not all the vowels of the strings read from a file.
This could easily be done with loop, but we were assigned to use recursions.

Jack and Jill went up the hill

Vowel Count = 7

My code so far:
#include <iostream>
using namespace std;

int vowelCount(string);

int main()
 string word;
 int vowelCounter = 0;
 cin >> word;
 while (!cin.eof())
    cin >> word;

cout << "Vowel Count = " << vowelCounter << endl;
return 0;

int vowelCount(string word)
 int length = word.length();
 int vowelCounter = 0;
 char ch;

 if (length==1)
     ch = tolower(s1[0]);
     if ((ch=='a')||(ch=='e')||(ch=='i')||(ch=='o')||(ch=='u'))

     vowelCounter = VowelCount(s1.substr(1));

 return vowelCounter;

Could you please tell me what am I doing wrong?
My output keeps saying 0.

Here I see where you declare vowelCounter and set it equal to 0, but you never use vowelCounter in the main code until you print the results at the end of the main program.  You call vowelCount but you never use or even store the integer that is returned.

If you use a statement like
vowelCounter += vowelCount(word);
instead, you will be able to count the number of vowels in each word and provide the total when you print out the result at the end of the main routine.


All Answers

Answers by Expert:

Ask Experts


Titus B. Ledbetter, Jr.


C , MFC, Object Oriented, Artificial Intelligence


I have over ten years experience in the field of Computer Science, five years experience developing C/C++. I recently wrote a chess program using Object Oriented, C++, MFC.

Master's Degree Computer Science from Johns Hopkins

©2016 All rights reserved.