Modifying my reverse a string function to add recursion. Unfortunately, my program keeps blowing up.
Stepped through my code in Visual Studio and for some reason the watch window will say i is equal to the length of the string (i.e. the terminating condition to exit the while loop). I step over it one last time and it says i is now one less than the string length. Then it stays in the while loop forever.
I know this sounds confusing, so I will give an example. I enter "Spongebob" and it does everything I want it to (i.e. says the length of Spongebob is 9, prints "bobegnopS", increments i to the string length, etc), but then it says i is now 8 (i.e. it was just at 9) and never exits the while loop.
Here is my ReverseString() function:
void ReverseString(char * string, bool stringReversed, int stringLength, int i)
{
i++;
if(!stringReversed)
{
while(*string != '\0')
string++;
}
stringReversed = true;
while(i < stringLength)
{
string--;
std::cout << *string;
ReverseString(string, stringReversed, stringLength, i);
}
}
Here is the call:
case 3:
//Learn By Doing 16.6
{
char string[BUFFER_LENGTH];
bool stringReversed = false;
int base = 0;
int exponent = 0;
std::cout << "\nEnter base: " << std::endl;
std::cin >> base;
std::cout << "\nEnter exponent: " << std::endl;
std::cin >> exponent;
//Print pow
NewLine();
std::cout << base << " to the " << exponent << " is " << pow(base, exponent);
//Reverse string using recursion
std::cout << "\nEnter string: " << std::endl;
std::cin >> string;
NewLine();
int stringLength = strlen(string);
int i = 0;
ReverseString(string, stringReversed, stringLength, i);
}