I am attempting to return a reversed version of the string "Loyce" in an iterative function. The program runs, but it crashes after running. Any help would be appreciated.
string Iterative4(string word)
{
for(int x = 0; x < word.length(); x++)
{
if (word.length() - 1 > 0)
{
char last_char = word[word.length() - 1];
word.erase(word.length() - 1);
string go = Iterative4(word);
return go;
}
}
}
int main() {
cout << Iterative4("Loyce") << endl;
}
std::reverse?Iterative4appears to be both iterative and recursive. I'm guessing that's not really what you want.std::reverseis of course no option (or maybe to be used in one of the implementations they should do).x? You call your functionIterative4recursively, so, probably, you solved problem recursively before and that is an artifact of your changes? Do something withxinstead. Second, you erase the last character from word, then you don't do anything with it. It will be lost. Since you want to reverse the string, I guess it's not too difficult for you to guess where you should put it ;-)