Write a recursive function that counts the number of a's in a string. Your program should include a driver that asks the user for a string, calls the recursive function, and outputs the number of a's it found in the string input by the user.
int countA(string, string);
int main()
{
string userInput;
string a = "a";
// Explain purpose of program to the user
cout <<"Purpose of this program is to count" << endl;
cout <<"the number of a's in a phrase inputted by the user\n" << endl;
// Asks the user for a string
cout << "Please enter a short phrase: ";
cin >> userInput;
// Call countA() in order to count the number of a's in the phrase
cout <<"The number of a's in the phrase is: " << countA(userInput, a) << endl;
system("PAUSE");
return 0;
}
int countA(string input, string a, )
{
int count = 0;
if(input != a)
{
return count;
}
else
{
count++;
return count + countA(input.substr(1), a);
//Have to use substring
}
}
I get 0 for my output. I think it's because I keep reinitializing count to 0 each time I go through but I'm not 100% sure. This is my first time with recursion and I understand the concept of it but I don't feel that I'm implementing it correctly here. Friendly advice appreciated.