I am required to use recursion to determine the number of occurrences of a certain character in a given string. Now the non-recursive function is very simple. But, when trying to use recursion, I am getting an error when my program runs
short f_r(string, char);
int main()
{
string str;
char c;
cout << "Enter a string: ";
getline(cin,str);
cout << "Enter a character: ";
cin >> c;
cout << "\nString: " << str << endl;
cout << f_r(str,c) << endl;
return 0;
}
short f_r(string str, char c)
{
int pos = 0;
pos = str.find(c, pos);
if (pos > str.length()) return 0;
else
{
int count = 0;
count++;
pos++;
return count + f_r(str,c);
}
}
f_rhas no viable break condition. It will always find the first char, and recurse with the same input data.std::string::findreturnsstd::string::nposwhen a value isn't found. You should test explicitly against that to decide if it failed to find something.