So I am trying to write a function that reverses a string in C++. I’ve figured out most of the code, and when I cout the string, its showing what I need. But when I test the code, the result is that I got: " from the function. Here’s my code:
#include <iostream>
#include <string>
using namespace std;
string result;
string reverseString (string str)
{
for(int i = str.length(); i >= -1; i--) {
result+= str[i];
}
cout << result;
return result;
}
>Solution :
In this for loop in the first its iteration
for(int i = str.length(); i >= -1; i--) {
result+= str[i];
}
the terminating zero character '\0' is written in the first position of the object result because the expression str[i] is equivalent in this case to the expression str[str.length()].
So the result string can be outputted as an empty string.
Also you are trying to access the source string using the negative index -1 that results in undefined behavior.
Instead of this for loop you could just write
result.assign( str.rbegin(), str.rend() );
If you want to do the task using the for loop then the loop can look for example the following way
result.clear();
result.reserve( str.length() );
for ( auto i = str.length(); i != 0; ) {
result += str[--i];
}
Pay attention to that it is a bad idea to use the global variable result within the function. The function could look like
std::string reverseString( const std::string &str )
{
return { str.rbegin(), str.rend() };
}