You are here:

C++/Vowel Count using Recursion

Advertisement


Question
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.

Input:
Jack and Jill went up the hill

Output:
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())
  {
    vowelCount(word);
    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++;
   }

 else
   {
     vowelCounter = VowelCount(s1.substr(1));
   }

 return vowelCounter;
}

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

Answer
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.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Titus B. Ledbetter, Jr.

Expertise

C , MFC, Object Oriented, Artificial Intelligence

Experience

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.

Education/Credentials
Master's Degree Computer Science from Johns Hopkins

©2016 About.com. All rights reserved.